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

__name_att__ = "websphere.resourceenventry.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sResourceEnvEntry:%(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('ResourceEnvEntry')

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenventry.name", objid, "name","ResourceEnvEntry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenventry.description", objid, "description","ResourceEnvEntry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenventry.category", objid, "category","ResourceEnvEntry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenventry.providertype", objid, "providerType","ResourceEnvEntry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.resourceenventry.jndiname", objid, "jndiName","ResourceEnvEntry");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  referenceable = Util.getOptionalAttribute(objid, 'referenceable', 'ResourceEnvEntry');
  if referenceable is not None and len(referenceable) > 0:
    returndict = Util.createTypeFolder(respath, "ReferenceableRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ReferenceableRef._export(referenceable, currespath, "Referenceable"));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.resourceenventry.name"):
    raise Exception("Resource role properties does not contain websphere.resourceenventry.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 ResourceEnvEntry on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.resourceenventry.name", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.resourceenventry.description", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.resourceenventry.category", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.resourceenventry.providertype", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.resourceenventry.jndiname", None));
  print "Creating ResourceEnvEntry with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ResourceEnvEntry", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereReferenceableRef":
        ReferenceableRef.create(objid, curjsonobject, "referenceable");
  Util.popPathElement('ResourceEnvEntry');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenventry.name", None), "name","ResourceEnvEntry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenventry.description", None), "description","ResourceEnvEntry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenventry.category", None), "category","ResourceEnvEntry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenventry.providertype", None), "providerType","ResourceEnvEntry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.resourceenventry.jndiname", None), "jndiName","ResourceEnvEntry");
  if len(atts) != 0:
    print "Modifying ResourceEnvEntry with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.unsetAttribute(objid, "referenceable", "ResourceEnvEntry");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereReferenceableRef":
        ReferenceableRef.create(objid, curjsonobject, "referenceable");

  Util.popPathElement('ResourceEnvEntry');
