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

__name_att__ = "websphere.resourceenvironmentprovider.name"

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'ResourceEnvironmentProvider');

  containmentpath = "%(parentconpath)sResourceEnvironmentProvider:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath);
  dict['conpath'] = containmentpath;
  return dict

def _export(objid, parentrespath):
  Util.pushPathElement('ResourceEnvironmentProvider')

  name = Util.getRequiredAttribute(objid, "name", 'ResourceEnvironmentProvider');


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

  roleProperties = JSONObject();

  Util.addAttributePathPropertyToJson(roleProperties, "websphere.resourceenvironmentprovider.classpath", objid, "classpath","ResourceEnvironmentProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenvironmentprovider.name", objid, "name","ResourceEnvironmentProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenvironmentprovider.isolatedclassloader", objid, "isolatedClassLoader","ResourceEnvironmentProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.resourceenvironmentprovider.nativepath", objid, "nativepath","ResourceEnvironmentProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenvironmentprovider.description", objid, "description","ResourceEnvironmentProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenvironmentprovider.providertype", objid, "providerType","ResourceEnvironmentProvider");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];

  typeFolders = {};
  
  i = 0;
  referenceables = Util.parseConfigIdListAttribute(objid, 'referenceables',"ResourceEnvironmentProvider");
  for referenceable in referenceables:
    if len(referenceable) > 0:
      returndict = Util.createTypeFolder(respath, "Referenceable", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, Referenceable._export(referenceable, currespath, "Referenceable%s" % i));
      i = i + 1;
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ResourceEnvironmentProvider');
  return result;



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

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

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    if parentid == None or len(parentid) == 0:
      raise Exception("Parent does not exist to create ResourceEnvironmentProvider on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.resourceenvironmentprovider.name"):
    raise Exception("Resource role properties does not contain websphere.resourceenvironmentprovider.name!");

  properties = [];
  Util.addPathProperty(properties, "classpath", roleProperties.optString("websphere.resourceenvironmentprovider.classpath", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.resourceenvironmentprovider.name", None));
  Util.addIfNotNone(properties, "isolatedClassLoader", roleProperties.optString("websphere.resourceenvironmentprovider.isolatedclassloader", None));
  Util.addPathProperty(properties, "nativepath", roleProperties.optString("websphere.resourceenvironmentprovider.nativepath", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.resourceenvironmentprovider.description", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.resourceenvironmentprovider.providertype", None));
  print "Creating ResourceEnvironmentProvider with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ResourceEnvironmentProvider", parentid, properties);
  
  referenceables = Util.parseConfigIdListAttribute(objid, 'referenceables',"ResourceEnvironmentProvider");
  for referenceable in referenceables:
    if len(referenceable) > 0:
      Util.remove(referenceable);    

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");   
      if currole == "WebSphereReferenceable":
        Referenceable.create(objid, curjsonobject);      
  Util.popPathElement('ResourceEnvironmentProvider');
  
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.resourceenvironmentprovider.name"):
    raise Exception("Resource role properties does not contain websphere.resourceenvironmentprovider.name!");

  atts = [];
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenvironmentprovider.classpath", None), "classpath","ResourceEnvironmentProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenvironmentprovider.name", None), "name","ResourceEnvironmentProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenvironmentprovider.isolatedclassloader", None), "isolatedClassLoader","ResourceEnvironmentProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenvironmentprovider.nativepath", None), "nativepath","ResourceEnvironmentProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenvironmentprovider.description", None), "description","ResourceEnvironmentProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenvironmentprovider.providertype", None), "providerType","ResourceEnvironmentProvider");
  if len(atts) != 0:
    print "Modifying ResourceEnvironmentProvider with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "ResourceEnvironmentProvider configuration up to date.";
    
  referenceables = Util.parseConfigIdListAttribute(objid, 'referenceables',"ResourceEnvironmentProvider");
  for referenceable in referenceables:
    if len(referenceable) > 0:
      Util.remove(referenceable);    
    
  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");   
      if currole == "WebSphereReferenceable":
        Referenceable.create(objid, curjsonobject);          

  Util.popPathElement('ResourceEnvironmentProvider');

def getReferenceables(objid):
  referenceables = Util.getAssociatedObjects(objid, "Referenceable");
  return referenceables;
