#- Licensed Materials - Property of IBM Corp.
#- IBM UrbanCode Deploy
#- (c) Copyright IBM Corporation 2014, 2015. All Rights Reserved.
#-
#- U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
#- GSA ADP Schedule Contract with IBM Corp.

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.wasqueueconnectionfactory.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

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

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

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