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

__name_att__ = "websphere.cmpconnectorfactory.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

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

  connPool = Util.getOptionalAttribute(objid, 'connectionPool', 'CMPConnectorFactory');
  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'));

  connDefinition = Util.getRequiredAttribute(objid, 'connectionDefinition', 'CMPConnectorFactory');
  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'));

  dataSource = Util.getOptionalAttribute(objid, 'cmpDatasource', 'CMPConnectorFactory');
  if dataSource is not None and len(dataSource) > 0:
    returndict = Util.createTypeFolder(respath, "DataSourceRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, DataSourceRef._export(dataSource, currespath));    
    
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('CMPConnectorFactory');
  return result;



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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  
  # connectionDefinition is a required attribute, and must to find out referenced ConnectionDefinition 
  # before new CMPConnectorFactory creation
  connDefinition = None;
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereConnectionDefinitionRef":
        #Only can pass parent J2CResourceAdapter ID to find ConnectionDefinition 
        connDefinition = ConnectionDefinitionRef.find(parentid, curjsonobject);
  if connDefinition == None:
    raise Exception("Could not find required Connection Definition reference for CMPConnectorFactory %(name)s" % { 'name':roleProperties.getString("websphere.cmpconnectorfactory.name")} );  
  Util.addIfNotNone(properties, "connectionDefinition", connDefinition);   
  # End of connectionDefinition creation  
  
  Util.addIfNotNone(properties, "logMissingTransactionContext", roleProperties.optString("websphere.cmpconnectorfactory.logmissingtransactioncontext", None));
  Util.addIfNotNone(properties, "authMechanismPreference", roleProperties.optString("websphere.cmpconnectorfactory.authmechanismpreference", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.cmpconnectorfactory.providertype", None));
  Util.addIfNotNone(properties, "authDataAlias", roleProperties.optString("websphere.cmpconnectorfactory.authdataalias", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.cmpconnectorfactory.jndiname", None));
  Util.addIfNotNone(properties, "manageCachedHandles", roleProperties.optString("websphere.cmpconnectorfactory.managecachedhandles", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.cmpconnectorfactory.category", None));
  Util.addIfNotNone(properties, "xaRecoveryAuthAlias", roleProperties.optString("websphere.cmpconnectorfactory.xarecoveryauthalias", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.cmpconnectorfactory.description", None));
  Util.addIfNotNone(properties, "diagnoseConnectionUsage", roleProperties.optString("websphere.cmpconnectorfactory.diagnoseconnectionusage", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.cmpconnectorfactory.name", None));
  print "Creating CMPConnectorFactory with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("CMPConnectorFactory", 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 == "WebSphereDataSourceRef":
        DataSourceRef.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CMPConnectorFactory');
       
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

  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", "CMPConnectorFactory");
      elif currole == "WebSphereDataSourceRef":
        DataSourceRef.create(objid, curjsonobject);        
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CMPConnectorFactory');
