from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from ConnectionPool import ConnectionPool
from ConnectionDefinitionRef import ConnectionDefinitionRef
from Property import Property

__name_att__ = "websphere.j2cconnectionfactory.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.logmissingtransactioncontext", objid, "logMissingTransactionContext","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.authmechanismpreference", objid, "authMechanismPreference","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.providertype", objid, "providerType","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.authdataalias", objid, "authDataAlias","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.jndiname", objid, "jndiName","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.managecachedhandles", objid, "manageCachedHandles","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.category", objid, "category","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.xarecoveryauthalias", objid, "xaRecoveryAuthAlias","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.description", objid, "description","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.diagnoseconnectionusage", objid, "diagnoseConnectionUsage","J2CConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2cconnectionfactory.name", objid, "name","J2CConnectionFactory");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"J2CConnectionFactory");

  connDefinition = Util.getRequiredAttribute(objid, 'connectionDefinition', 'J2CConnectionFactory');
  if connDefinition is not None and len(connDefinition) > 0:
    returndict = Util.createTypeFolder(respath, "ConnectionDefinitionRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ConnectionDefinitionRef._export(connDefinition, currespath, 'Connection Definition'));

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

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "logMissingTransactionContext", roleProperties.optString("websphere.j2cconnectionfactory.logmissingtransactioncontext", None));
  Util.addIfNotNone(properties, "authMechanismPreference", roleProperties.optString("websphere.j2cconnectionfactory.authmechanismpreference", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.j2cconnectionfactory.providertype", None));
  Util.addIfNotNone(properties, "authDataAlias", roleProperties.optString("websphere.j2cconnectionfactory.authdataalias", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.j2cconnectionfactory.jndiname", None));
  Util.addIfNotNone(properties, "manageCachedHandles", roleProperties.optString("websphere.j2cconnectionfactory.managecachedhandles", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.j2cconnectionfactory.category", None));
  Util.addIfNotNone(properties, "xaRecoveryAuthAlias", roleProperties.optString("websphere.j2cconnectionfactory.xarecoveryauthalias", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.j2cconnectionfactory.description", None));
  Util.addIfNotNone(properties, "diagnoseConnectionUsage", roleProperties.optString("websphere.j2cconnectionfactory.diagnoseconnectionusage", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.j2cconnectionfactory.name", None));
  print "Creating J2CConnectionFactory with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("J2CConnectionFactory", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereConnectionPool":
        ConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereConnectionDefinitionRef":
        ConnectionDefinitionRef.create(objid, curjsonobject, "connectionDefinition", "J2CConnectionFactory");
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('J2CConnectionFactory');

  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.logmissingtransactioncontext", None), "logMissingTransactionContext","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.authmechanismpreference", None), "authMechanismPreference","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.providertype", None), "providerType","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.authdataalias", None), "authDataAlias","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.jndiname", None), "jndiName","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.managecachedhandles", None), "manageCachedHandles","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.category", None), "category","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.xarecoveryauthalias", None), "xaRecoveryAuthAlias","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.description", None), "description","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.diagnoseconnectionusage", None), "diagnoseConnectionUsage","J2CConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2cconnectionfactory.name", None), "name","J2CConnectionFactory");
  if len(atts) != 0:
    print "Modifying J2CConnectionFactory with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.unsetAttribute(objid, 'connectionDefinition',"J2CConnectionFactory");

  connPool = Util.getOptionalAttribute(objid, 'connectionPool', 'J2CConnectionFactory');
  if connPool is not None and len(connPool) > 0:
    Util.remove(connPool);

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereConnectionPool":
        ConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereConnectionDefinitionRef":
        ConnectionDefinitionRef.create(objid, curjsonobject, "connectionDefinition", "J2CConnectionFactory");
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);

  Util.popPathElement('J2CConnectionFactory');
