###
# 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 ModuleMapping import ModuleMapping

__name_att__ = "websphere.wastopicconnectionfactory.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.logmissingtransactioncontext", objid, "logMissingTransactionContext","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.xaenabled", objid, "XAEnabled","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.authmechanismpreference", objid, "authMechanismPreference","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.providertype", objid, "providerType","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.servername", objid, "serverName","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.authdataalias", objid, "authDataAlias","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.port", objid, "port","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.clonesupport", objid, "cloneSupport","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.jndiname", objid, "jndiName","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.clientid", objid, "clientID","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.managecachedhandles", objid, "manageCachedHandles","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.node", objid, "node","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.category", objid, "category","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.xarecoveryauthalias", objid, "xaRecoveryAuthAlias","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.description", objid, "description","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.diagnoseconnectionusage", objid, "diagnoseConnectionUsage","WASTopicConnectionFactory");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wastopicconnectionfactory.name", objid, "name","WASTopicConnectionFactory");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"WASTopicConnectionFactory");
  connPool = Util.getOptionalAttribute(objid, 'connectionPool', 'WASTopicConnectionFactory');
  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', 'WASTopicConnectionFactory');
  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', 'WASTopicConnectionFactory');
  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('WASTopicConnectionFactory');
  return result;



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "logMissingTransactionContext", roleProperties.optString("websphere.wastopicconnectionfactory.logmissingtransactioncontext", None));
  Util.addIfNotNone(properties, "XAEnabled", roleProperties.optString("websphere.wastopicconnectionfactory.xaenabled", None));
  Util.addIfNotNone(properties, "authMechanismPreference", roleProperties.optString("websphere.wastopicconnectionfactory.authmechanismpreference", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.wastopicconnectionfactory.providertype", None));
  Util.addIfNotNone(properties, "serverName", roleProperties.optString("websphere.wastopicconnectionfactory.servername", None));
  Util.addIfNotNone(properties, "authDataAlias", roleProperties.optString("websphere.wastopicconnectionfactory.authdataalias", None));
  Util.addIfNotNone(properties, "port", roleProperties.optString("websphere.wastopicconnectionfactory.port", None));
  Util.addIfNotNone(properties, "cloneSupport", roleProperties.optString("websphere.wastopicconnectionfactory.clonesupport", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.wastopicconnectionfactory.jndiname", None));
  Util.addIfNotNone(properties, "clientID", roleProperties.optString("websphere.wastopicconnectionfactory.clientid", None));
  Util.addIfNotNone(properties, "manageCachedHandles", roleProperties.optString("websphere.wastopicconnectionfactory.managecachedhandles", None));
  Util.addIfNotNone(properties, "node", roleProperties.optString("websphere.wastopicconnectionfactory.node", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.wastopicconnectionfactory.category", None));
  Util.addIfNotNone(properties, "xaRecoveryAuthAlias", roleProperties.optString("websphere.wastopicconnectionfactory.xarecoveryauthalias", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.wastopicconnectionfactory.description", None));
  Util.addIfNotNone(properties, "diagnoseConnectionUsage", roleProperties.optString("websphere.wastopicconnectionfactory.diagnoseconnectionusage", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.wastopicconnectionfactory.name", None));
  print "Creating WASTopicConnectionFactory with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("WASTopicConnectionFactory", 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('WASTopicConnectionFactory');

  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.logmissingtransactioncontext", None), "logMissingTransactionContext","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.xaenabled", None), "XAEnabled","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.authmechanismpreference", None), "authMechanismPreference","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.providertype", None), "providerType","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.servername", None), "serverName","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.authdataalias", None), "authDataAlias","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.port", None), "port","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.clonesupport", None), "cloneSupport","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.jndiname", None), "jndiName","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.clientid", None), "clientID","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.managecachedhandles", None), "manageCachedHandles","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.node", None), "node","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.category", None), "category","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.xarecoveryauthalias", None), "xaRecoveryAuthAlias","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.description", None), "description","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.diagnoseconnectionusage", None), "diagnoseConnectionUsage","WASTopicConnectionFactory");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.wastopicconnectionfactory.name", None), "name","WASTopicConnectionFactory");
  if len(atts) != 0:
    print "Modifying WASTopicConnectionFactory with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

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

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

  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('WASTopicConnectionFactory');
