from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from DeploymentTargetMapping import DeploymentTargetMapping
from Property import Property
from Classloader import Classloader

__name_att__ = None;

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


  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 WebSphereApplicationDeployment");
  exportedObject.put("roleName", "WebSphereApplicationDeployment");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.recycleonupdate", objid, "recycleOnUpdate","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.standalonemodule", objid, "standaloneModule","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.allowdispatchremoteinclude", objid, "allowDispatchRemoteInclude","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.autolink", objid, "autoLink","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.zerobinarycopy", objid, "zeroBinaryCopy","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.expandsynchronously", objid, "expandSynchronously","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.allowserviceremoteinclude", objid, "allowServiceRemoteInclude","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.warclassloaderpolicy", objid, "warClassLoaderPolicy","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.asyncrequestdispatchtype", objid, "asyncRequestDispatchType","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.filepermission", objid, "filePermission","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.enabledistribution", objid, "enableDistribution","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.startingweight", objid, "startingWeight","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.deploymentid", objid, "deploymentId","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.zeroearcopy", objid, "zeroEarCopy","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.backgroundapplication", objid, "backgroundApplication","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.reloadinterval", objid, "reloadInterval","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.usemetadatafrombinaries", objid, "useMetadataFromBinaries","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.reloadenabled", objid, "reloadEnabled","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.appcontextidforsecurity", objid, "appContextIDForSecurity","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.enableclientmodule", objid, "enableClientModule","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.creatembeansforresources", objid, "createMBeansForResources","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.binariesurl", objid, "binariesURL","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.startondistribute", objid, "startOnDistribute","ApplicationDeployment");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationdeployment.name", objid, "name","ApplicationDeployment");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  i = 0;
  targetmappings = Util.parseConfigIdListAttribute(objid, 'targetMappings',"ApplicationDeployment");
  typeFolders = {};
  for targetmapping in targetmappings:
    if len(targetmapping) > 0:
      returndict = Util.createTypeFolder(respath, "DeploymentTargetMapping", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, DeploymentTargetMapping._export(targetmapping, currespath, "DeploymentTargetMapping%s" % i));
      i = i + 1;
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"ApplicationDeployment");
  
  classloader = Util.getRequiredAttribute(objid, 'classloader',"ApplicationDeployment");
  if classloader is not None and len(classloader) > 0:
    returndict = Util.createTypeFolder(respath, "Classloader", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, Classloader._export(classloader, currespath, "Classloader"));
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ApplicationDeployment');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "recycleOnUpdate", roleProperties.optString("websphere.applicationdeployment.recycleonupdate", None));
  Util.addIfNotNone(properties, "standaloneModule", roleProperties.optString("websphere.applicationdeployment.standalonemodule", None));
  Util.addIfNotNone(properties, "allowDispatchRemoteInclude", roleProperties.optString("websphere.applicationdeployment.allowdispatchremoteinclude", None));
  Util.addIfNotNone(properties, "autoLink", roleProperties.optString("websphere.applicationdeployment.autolink", None));
  Util.addIfNotNone(properties, "zeroBinaryCopy", roleProperties.optString("websphere.applicationdeployment.zerobinarycopy", None));
  Util.addIfNotNone(properties, "expandSynchronously", roleProperties.optString("websphere.applicationdeployment.expandsynchronously", None));
  Util.addIfNotNone(properties, "allowServiceRemoteInclude", roleProperties.optString("websphere.applicationdeployment.allowserviceremoteinclude", None));
  Util.addIfNotNone(properties, "warClassLoaderPolicy", roleProperties.optString("websphere.applicationdeployment.warclassloaderpolicy", None));
  Util.addIfNotNone(properties, "asyncRequestDispatchType", roleProperties.optString("websphere.applicationdeployment.asyncrequestdispatchtype", None));
  Util.addIfNotNone(properties, "filePermission", roleProperties.optString("websphere.applicationdeployment.filepermission", None));
  Util.addIfNotNone(properties, "enableDistribution", roleProperties.optString("websphere.applicationdeployment.enabledistribution", None));
  Util.addIfNotNone(properties, "startingWeight", roleProperties.optString("websphere.applicationdeployment.startingweight", None));
  Util.addIfNotNone(properties, "deploymentId", roleProperties.optString("websphere.applicationdeployment.deploymentid", None));
  Util.addIfNotNone(properties, "zeroEarCopy", roleProperties.optString("websphere.applicationdeployment.zeroearcopy", None));
  Util.addIfNotNone(properties, "backgroundApplication", roleProperties.optString("websphere.applicationdeployment.backgroundapplication", None));
  Util.addIfNotNone(properties, "reloadInterval", roleProperties.optString("websphere.applicationdeployment.reloadinterval", None));
  Util.addIfNotNone(properties, "useMetadataFromBinaries", roleProperties.optString("websphere.applicationdeployment.usemetadatafrombinaries", None));
  Util.addIfNotNone(properties, "reloadEnabled", roleProperties.optString("websphere.applicationdeployment.reloadenabled", None));
  Util.addIfNotNone(properties, "appContextIDForSecurity", roleProperties.optString("websphere.applicationdeployment.appcontextidforsecurity", None));
  Util.addIfNotNone(properties, "enableClientModule", roleProperties.optString("websphere.applicationdeployment.enableclientmodule", "false"));
  Util.addIfNotNone(properties, "createMBeansForResources", roleProperties.optString("websphere.applicationdeployment.creatembeansforresources", None));
  Util.addIfNotNone(properties, "binariesURL", roleProperties.optString("websphere.applicationdeployment.binariesurl", None));
  Util.addIfNotNone(properties, "startOnDistribute", roleProperties.optString("websphere.applicationdeployment.startondistribute", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.applicationdeployment.name", ""));
  print "Creating ApplicationDeployment with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ApplicationDeployment", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereDeploymentTargetMapping":
        DeploymentTargetMapping.create(objid, curjsonobject);
      elif currole == "WebSphereClassloader":
        Classloader.create(objid, curjsonobject);
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('ApplicationDeployment');


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.recycleonupdate", None), "recycleOnUpdate","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.standalonemodule", None), "standaloneModule","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.allowdispatchremoteinclude", None), "allowDispatchRemoteInclude","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.autolink", None), "autoLink","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.zerobinarycopy", None), "zeroBinaryCopy","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.expandsynchronously", None), "expandSynchronously","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.allowserviceremoteinclude", None), "allowServiceRemoteInclude","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.warclassloaderpolicy", None), "warClassLoaderPolicy","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.asyncrequestdispatchtype", None), "asyncRequestDispatchType","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.filepermission", None), "filePermission","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.enabledistribution", None), "enableDistribution","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.startingweight", None), "startingWeight","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.deploymentid", None), "deploymentId","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.zeroearcopy", None), "zeroEarCopy","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.backgroundapplication", None), "backgroundApplication","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.reloadinterval", None), "reloadInterval","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.usemetadatafrombinaries", None), "useMetadataFromBinaries","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.reloadenabled", None), "reloadEnabled","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.appcontextidforsecurity", None), "appContextIDForSecurity","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.enableclientmodule", "false"), "enableClientModule","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.creatembeansforresources", None), "createMBeansForResources","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.binariesurl", None), "binariesURL","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.startondistribute", None), "startOnDistribute","ApplicationDeployment");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationdeployment.name", ""), "name","ApplicationDeployment");
  if len(atts) != 0:
    print "Modifying ApplicationDeployment with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  targetmappings = Util.parseConfigIdListAttribute(objid, 'targetMappings',"ApplicationDeployment");
  for targetmapping in targetmappings:
    if len(targetmapping) > 0:
      Util.remove(targetmapping);
      
  classloader = Util.getRequiredAttribute(objid, 'classloader',"ApplicationDeployment");
  if classloader is not None and len(classloader) > 0:
    Util.remove(classloader);
    
  Property.removeProperties(objid, 'properties',"ApplicationDeployment");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereDeploymentTargetMapping":
        DeploymentTargetMapping.create(objid, curjsonobject);
      elif currole == "WebSphereClassloader":
        Classloader.create(objid, curjsonobject);
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('ApplicationDeployment');
