from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from WASConfLog import Log;
from utilities import Util

__name_att__ = "websphere.proxyvirtualhostref.virtualhostname"

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('ProxyVirtualHostRef')

  if name == "":
    name = Util.getRequiredAttribute(objid, "virtualHostName", "ProxyVirtualHost");
  if parentrespath == "/":
    parentrespath = "";
  respath = "%(parentrespath)s/%(name)s" % { 'parentrespath':parentrespath, 'name':name }
  if not respath.startswith("/"):
    respath = "/" + respath;

  exportedObject = JSONObject();
  exportedObject.put("name", name);
  exportedObject.put("path", respath);
  exportedObject.put("teamMappings", JSONArray());
  exportedObject.put("inheritTeam", "true");
  exportedObject.put("description", "Discovered WebSphereProxyVirtualHostRef");
  exportedObject.put("roleName", "WebSphereProxyVirtualHostRef");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.proxyvirtualhostref.virtualhostname", objid, "virtualHostName","ProxyVirtualHost");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ProxyVirtualHostRef');
  return result;


def doImport(parentid, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("WebSphereProxyVirtualHostRef resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.proxyvirtualhostref.virtualhostname"):
    raise Exception("Resource role properties does not contain websphere.proxyvirtualhostref.virtualhostname!");

  targetProxyVirtualHostName = roleProperties.optString("websphere.proxyvirtualhostref.virtualhostname", None);

  proxyVirtualHosts = Util.parseConfigIdListAttribute(parentid, 'proxyVirtualHosts',"ProxyVirtualHostConfig");
  Util.pushPathElement("Server");
  Util.pushPathElement("ProxyVirtualHostConfig")
  for proxyVirtualHost in proxyVirtualHosts:
    if len(proxyVirtualHost) > 0:
      proxyVirtualHostName = Util.getRequiredAttribute(proxyVirtualHost, "virtualHostName", "ProxyVirtualHost");
      if targetProxyVirtualHostName == proxyVirtualHostName:
        Util.modify(parentid, [['enabledProxyVirtualHosts', proxyVirtualHost]]);
        break;
  Util.popPathElement("ProxyVirtualHostConfig")
  Util.popPathElement("Server");
