package com.google.sampling.experiential.server;

import java.util.Set;

import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.modules.ModulesServiceFactory;

public class PacoModule {
  String name;
  String address;
  ModulesService modulesApi = ModulesServiceFactory.getModulesService();
  private static final String DOT = "-dot-";
  private static final String LOCALHOST = "localhost";
  
  public PacoModule(String moduleName, String serverName) {
    this.name = moduleName;
    Set<String> allModules = modulesApi.getModules();
    String version = null;
    String serverNameInParts[] = null;
    String finalUrl = null;
    if (LOCALHOST.equalsIgnoreCase(serverName)) {
      finalUrl = modulesApi.getVersionHostname(name, modulesApi.getDefaultVersion(name));
    } else {
      for (String eachModuleName : allModules) {
        if (eachModuleName != null && eachModuleName.equalsIgnoreCase(name)) { 
          // Eg: If server name has -dot- in its request url
          if (serverName != null && serverName.contains(DOT)) {
            serverNameInParts = serverName.split(DOT);
            // Eg: 221-dot-quantifiedself.appspot.com
            if (serverNameInParts != null && serverNameInParts.length == 2) {
              finalUrl = serverNameInParts[0] + DOT + name + DOT + serverNameInParts[1];
            } else if(serverNameInParts.length == 3) {
              //Eg: 221-dot-default-dot-quantifiedself.appspot.com
              serverNameInParts = serverName.split(DOT);
              finalUrl =  serverNameInParts[0] + DOT + name + DOT + serverNameInParts[2];
            } else {
              finalUrl = "";
            }
          } else {
            //Eg: quantifiedself.com
            version = modulesApi.getCurrentVersion();
            finalUrl = version + DOT + name + DOT + serverName;
          }
          break;
        } else {
          finalUrl = "";
        }
      }
    }
    this.address = finalUrl;
  }
  
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getAddress() {
    return address;
  }
  public void setAddress(String address) {
    this.address = address;
  }
  
}

@@ -418,19 +418,17 @@
 lhost%22;%0A
-  
 %0A
+
   public
@@ -935,17 +935,16 @@
 name)) %7B
- 
 %0A       
@@ -1705,149 +1705,102 @@
     
-//Eg: quantifiedself.com%0A            version = modulesApi.getCurrentVersion();%0A            finalUrl = version + DOT + name + DOT + server
+finalUrl = modulesApi.getVersionHostname(moduleName, modulesApi.getDefaultVersion(module
 Name
+))
 ;%0A  
@@ -1925,19 +1925,17 @@
 rl;%0A  %7D%0A
-  
 %0A
+
   public
@@ -2168,13 +2168,11 @@
 ss;%0A  %7D%0A
-  
 %0A%7D%0A

compute the target appengine module name in prod