###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2014, 2015, 2017. All Rights Reserved.
# (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
#
# U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
# GSA ADP Schedule Contract with IBM Corp.
#
# * Trademark of International Business Machines
# ** Trademark of HCL Technologies Limited

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

__name_att__ = "websphere.genericjmsconnectionfactory.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

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

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

  sessPool = Util.getOptionalAttribute(objid, 'sessionPool', 'GenericJMSConnectionFactory');
  if sessPool is not None and len(sessPool) > 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(sessPool, currespath, 'SessionPool'));

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

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "logMissingTransactionContext", roleProperties.optString("websphere.genericjmsconnectionfactory.logmissingtransactioncontext", None));
  Util.addIfNotNone(properties, "type", roleProperties.optString("websphere.genericjmsconnectionfactory.type", None));
  Util.addIfNotNone(properties, "XAEnabled", roleProperties.optString("websphere.genericjmsconnectionfactory.xaenabled", None));
  Util.addIfNotNone(properties, "authMechanismPreference", roleProperties.optString("websphere.genericjmsconnectionfactory.authmechanismpreference", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.genericjmsconnectionfactory.providertype", None));
  Util.addIfNotNone(properties, "authDataAlias", roleProperties.optString("websphere.genericjmsconnectionfactory.authdataalias", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.genericjmsconnectionfactory.jndiname", None));
  Util.addIfNotNone(properties, "externalJNDIName", roleProperties.optString("websphere.genericjmsconnectionfactory.externaljndiname", None));
  Util.addIfNotNone(properties, "manageCachedHandles", roleProperties.optString("websphere.genericjmsconnectionfactory.managecachedhandles", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.genericjmsconnectionfactory.category", None));
  Util.addIfNotNone(properties, "xaRecoveryAuthAlias", roleProperties.optString("websphere.genericjmsconnectionfactory.xarecoveryauthalias", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.genericjmsconnectionfactory.description", None));
  Util.addIfNotNone(properties, "diagnoseConnectionUsage", roleProperties.optString("websphere.genericjmsconnectionfactory.diagnoseconnectionusage", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.genericjmsconnectionfactory.name", None));
  print "Creating GenericJMSConnectionFactory with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("GenericJMSConnectionFactory", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereConnectionPool":
        poolname = curjsonobject.getString("name");
        if poolname == "ConnectionPool":
          ConnectionPool.create(objid, curjsonobject, "connectionPool");
        elif poolname == "SessionPool":
          ConnectionPool.create(objid, curjsonobject, "sessionPool");
        else:
          ConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereMappingModule":
        MappingModule.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('GenericJMSConnectionFactory');

  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

  sessPool = Util.getOptionalAttribute(objid, 'sessionPool', 'GenericJMSConnectionFactory');
  if sessPool is not None and len(sessPool) > 0:
    Util.remove(sessPool);

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereConnectionPool":
        poolname = curjsonobject.getString("name");
        if poolname == "ConnectionPool":
          ConnectionPool.create(objid, curjsonobject, "connectionPool");
        elif poolname == "SessionPool":
          ConnectionPool.create(objid, curjsonobject, "sessionPool");
        else:
          ConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereMappingModule":
        MappingModule.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('GenericJMSConnectionFactory');
