from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from ProxyVirtualHostSettings import ProxyVirtualHostSettings
from ProxyRuleExpressionRef import ProxyRuleExpressionRef

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('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 WebSphereProxyVirtualHost");
  exportedObject.put("roleName", "WebSphereProxyVirtualHost");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.proxyvirtualhost.virtualhostname", objid, "virtualHostName","ProxyVirtualHost");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.proxyvirtualhost.virtualhostport", objid, "virtualHostPort","ProxyVirtualHost");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  proxyRuleExpressionRefs = Util.parseConfigIdListAttribute(objid, 'enabledProxyRuleExpressions',"ProxyVirtualHost");
  for proxyRuleExpressionRef in proxyRuleExpressionRefs:
    if len(proxyRuleExpressionRef) > 0:
      returndict = Util.createTypeFolder(respath, "ProxyRuleExpressionRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
       Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ProxyRuleExpressionRef._export(proxyRuleExpressionRef, currespath, "Proxy Rule Expressions Ref%s" % i));
      i = i + 1;

  proxyVirtualHostSettings = Util.getRequiredAttribute(objid, 'proxyVirtualHostSettings',"ProxyVirtualHost");
  if proxyVirtualHostSettings is not None and len(proxyVirtualHostSettings) > 0:
    returndict = Util.createTypeFolder(respath, "ProxyVirtualHostSettings", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ProxyVirtualHostSettings._export(proxyVirtualHostSettings, currespath, "Proxy Virtual Host Settings"));

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"ProxyVirtualHost","PropertyAttrs");

  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ProxyVirtualHost');
  return result;



def create(parentid, jsonobject, attName):
  Util.pushPathElement('ProxyVirtualHost')
  if not jsonobject.has("roleProperties"):
    raise Exception("ProxyVirtualHost resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "virtualHostName", roleProperties.optString("websphere.proxyvirtualhost.virtualhostname", None));
  Util.addIfNotNone(properties, "virtualHostPort", roleProperties.optString("websphere.proxyvirtualhost.virtualhostport", None));
  print "Creating ProxyVirtualHost with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ProxyVirtualHost", parentid, properties, attName);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereProxyRuleExpressionRef":
        ProxyRuleExpressionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereProxyVirtualHostSettings":
        ProxyVirtualHostSettings.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('ProxyVirtualHost');

def update(objid,jsonobject):
  Util.pushPathElement('ProxyVirtualHost')
  if not jsonobject.has("roleProperties"):
    raise Exception("ProxyVirtualHost resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.proxyvirtualhost.virtualhostname", None), "virtualHostName","ProxyVirtualHost");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.proxyvirtualhost.virtualhostport", None), "virtualHostPort","ProxyVirtualHost");
  if len(atts) != 0:
    print "Modifying ProxyVirtualHost with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "ProxyVirtualHost configuration up to date.";

  proxyRuleExpressions = Util.parseConfigIdListAttribute(objid, 'enabledProxyRuleExpressions',"ProxyVirtualHost");
  for proxyRuleExpression in proxyRuleExpressions:
    if len(proxyRuleExpression) > 0:
      Util.remove(proxyRuleExpression);

  Property.removeProperties(objid, 'properties',"ProxyVirtualHost");

  proxyVirtualHostSettings = Util.getRequiredAttribute(objid, 'proxyVirtualHostSettings',"ProxyVirtualHost");
  if proxyVirtualHostSettings is not None and len(proxyVirtualHostSettings) > 0:
    Util.remove(proxyVirtualHostSettings);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereProxyRuleExpressionRef":
        ProxyRuleExpressionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereProxyVirtualHostSettings":
        ProxyVirtualHostSettings.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('ProxyVirtualHost');
