###
# 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 Description import Description
from DisplayName import DisplayName
from IconType import IconType
from DataSourceDefinition import DataSourceDefinition
from EnvEntry import EnvEntry
from MessageDestinationRef import MessageDestinationRef
from PersistenceContextRef import PersistenceContextRef
from PersistenceUnitRef import PersistenceUnitRef
from ResourceRef import ResourceRef
from ResourceEnvRef import ResourceEnvRef
from LifecycleCallbackType import LifecycleCallbackType
from EJBLocalRef import EJBLocalRef
from EjbRef import EjbRef

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('JNDIEnvRefsGroup')


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jndienvrefsgroup.largeicon", objid, "largeIcon","JNDIEnvRefsGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jndienvrefsgroup.displayname", objid, "displayName","JNDIEnvRefsGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jndienvrefsgroup.smallicon", objid, "smallIcon","JNDIEnvRefsGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jndienvrefsgroup.description", objid, "description","JNDIEnvRefsGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  descriptions = Util.parseConfigIdListAttribute(objid, 'descriptions', 'JNDIEnvRefsGroup');
  for description in descriptions:
    if len(description) > 0:
      returndict = Util.createTypeFolder(respath, "Description", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, Description._export(description, currespath, "Description%s" % i));
      i = i + 1;

  i = 0;
  displayNames = Util.parseConfigIdListAttribute(objid, 'displayNames', 'JNDIEnvRefsGroup');
  for displayName in displayNames:
    if len(displayName) > 0:
      returndict = Util.createTypeFolder(respath, "DisplayName", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, DisplayName._export(displayName, currespath, "DisplayName%s" % i));
      i = i + 1;

  i = 0;
  icons = Util.parseConfigIdListAttribute(objid, 'icons', 'JNDIEnvRefsGroup');
  for icon in icons:
    if len(icon) > 0:
      returndict = Util.createTypeFolder(respath, "IconType", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, IconType._export(icon, currespath, "Icon%s" % i));
      i = i + 1;

  i = 0;
  dataSources = Util.parseConfigIdListAttribute(objid, 'dataSources',"JNDIEnvRefsGroup");
  for dataSource in dataSources:
    if len(dataSource) > 0:
      returndict = Util.createTypeFolder(respath, "DataSourceDefinition", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      dataSourceName = Util.getOptionalAttribute(dataSource, "name", "DataSourceDefinition");
      if dataSourceName == None or len(dataSourceName) == 0:
        dataSourceName = ("DataSourceDefinition%s" % i)
      Util.addAllFromExport(extraObjects, DataSourceDefinition._export(dataSource, currespath, dataSourceName));
      i = i + 1;

  i = 0;
  environmentProperties = Util.parseConfigIdListAttribute(objid, 'environmentProperties',"JNDIEnvRefsGroup");
  for environmentProperty in environmentProperties:
    if len(environmentProperty) > 0:
      returndict = Util.createTypeFolder(respath, "EnvEntry", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      environmentPropertyName = Util.getOptionalAttribute(environmentProperty, "name", "EnvEntry");
      if environmentPropertyName == None or len(environmentPropertyName) == 0:
        environmentPropertyName = ("EnvEntry%s" % i)
      Util.addAllFromExport(extraObjects, EnvEntry._export(environmentProperty, currespath, environmentPropertyName));
      i = i + 1;

  i = 0;
  messageDestinationRefs = Util.parseConfigIdListAttribute(objid, 'messageDestinationRefs',"JNDIEnvRefsGroup");
  for messageDestinationRef in messageDestinationRefs:
    if len(messageDestinationRef) > 0:
      returndict = Util.createTypeFolder(respath, "MessageDestinationRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      messageDestinationRefName = Util.getOptionalAttribute(messageDestinationRef, "name", "MessageDestinationRef");
      if messageDestinationRefName == None or len(messageDestinationRefName) == 0:
        messageDestinationRefName = ("MessageDestinationRef%s" % i)
      Util.addAllFromExport(extraObjects, MessageDestinationRef._export(messageDestinationRef, currespath, messageDestinationRefName));
      i = i + 1;

  i = 0;
  persistenceContextRefs = Util.parseConfigIdListAttribute(objid, 'persistenceContextRefs',"JNDIEnvRefsGroup");
  for persistenceContextRef in persistenceContextRefs:
    if len(persistenceContextRef) > 0:
      returndict = Util.createTypeFolder(respath, "PersistenceContextRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      persistenceContextRefName = Util.getOptionalAttribute(persistenceContextRef, "name", "PersistenceContextRef");
      if persistenceContextRefName == None or len(persistenceContextRefName) == 0:
        persistenceContextRefName = ("PersistenceContextRef%s" % i)
      Util.addAllFromExport(extraObjects, PersistenceContextRef._export(persistenceContextRef, currespath, persistenceContextRefName));

  i = 0;
  persistenceUnitRefs = Util.parseConfigIdListAttribute(objid, 'persistenceUnitRefs',"JNDIEnvRefsGroup");
  for persistenceUnitRef in persistenceUnitRefs:
    if len(persistenceUnitRef) > 0:
      returndict = Util.createTypeFolder(respath, "PersistenceUnitRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      persistenceUnitRefName = Util.getOptionalAttribute(persistenceUnitRef, "name", "PersistenceUnitRef");
      if persistenceUnitRefName == None or len(persistenceUnitRefName) == 0:
        persistenceUnitRefName = ("PersistenceUnitRef%s" % i)
      Util.addAllFromExport(extraObjects, PersistenceUnitRef._export(persistenceUnitRef, currespath, persistenceUnitRefName));

  i = 0;
  resourceEnvRefs = Util.parseConfigIdListAttribute(objid, 'resourceEnvRefs',"JNDIEnvRefsGroup");
  for resourceEnvRef in resourceEnvRefs:
    if len(resourceEnvRef) > 0:
      returndict = Util.createTypeFolder(respath, "ResourceEnvRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      resourceEnvRefName = Util.getOptionalAttribute(resourceEnvRef, "name", "ResourceEnvRef");
      if resourceEnvRefName == None or len(resourceEnvRefName) == 0:
        resourceEnvRefName = ("ResourceEnvRef%s" % i)
      Util.addAllFromExport(extraObjects, ResourceEnvRef._export(resourceEnvRef, currespath, resourceEnvRefName));

  i = 0;
  resourceRefs = Util.parseConfigIdListAttribute(objid, 'resourceRefs',"JNDIEnvRefsGroup");
  for resourceRef in resourceRefs:
    if len(resourceRef) > 0:
      returndict = Util.createTypeFolder(respath, "ResourceRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      resourceRefName = Util.getOptionalAttribute(resourceRef, "name", "ResourceRef");
      if resourceRefName == None or len(resourceRefName) == 0:
        resourceRefName = ("ResourceRef%s" % i)
      Util.addAllFromExport(extraObjects, ResourceRef._export(resourceRef, currespath, resourceRefName));

  i = 0;
  postConstructs = Util.parseConfigIdListAttribute(objid, 'postConstruct',"JNDIEnvRefsGroup");
  for postConstruct in postConstructs:
    if len(postConstruct) > 0:
      returndict = Util.createTypeFolder(respath, "PostConstruct", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      postConstructName = Util.getOptionalAttribute(postConstruct, "methodName", "LifecycleCallbackType");
      if postConstructName == None or len(postConstructName) == 0:
        postConstructName = ("LifecycleCallbackType%s" % i)
      Util.addAllFromExport(extraObjects, LifecycleCallbackType._export(postConstruct, currespath, postConstructName));

  i = 0;
  preDestroys = Util.parseConfigIdListAttribute(objid, 'preDestroy',"JNDIEnvRefsGroup");
  for preDestroy in preDestroys:
    if len(preDestroy) > 0:
      returndict = Util.createTypeFolder(respath, "PreDestroy", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      preDestroyName = Util.getOptionalAttribute(preDestroy, "methodName", "LifecycleCallbackType");
      if preDestroyName == None or len(preDestroyName) == 0:
        preDestroyName = ("LifecycleCallbackType%s" % i)
      Util.addAllFromExport(extraObjects, LifecycleCallbackType._export(preDestroy, currespath, preDestroyName));

  i = 0;
  ejbLocalRefs = Util.parseConfigIdListAttribute(objid, 'ejbLocalRefs',"JNDIEnvRefsGroup");
  for ejbLocalRef in ejbLocalRefs:
    if len(ejbLocalRef) > 0:
      returndict = Util.createTypeFolder(respath, "EJBLocalRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      ejbLocalRefName = Util.getOptionalAttribute(ejbLocalRef, "name", "EBJLocalRef");
      if ejbLocalRefName == None or len(ejbLocalRefName) == 0:
        ejbLocalRefName = ("EJBLocalRef%s" % i)
      Util.addAllFromExport(extraObjects, EJBLocalRef._export(ejbLocalRef, currespath, ejbLocalRefName));

  i = 0;
  ejbRefs = Util.parseConfigIdListAttribute(objid, 'ejbRefs',"JNDIEnvRefsGroup");
  for ejbRef in ejbRefs:
    if len(ejbRef) > 0:
      returndict = Util.createTypeFolder(respath, "EjbRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      if ejbRef.find("#EjbRef_") > 0:
        ejbRefName = Util.getOptionalAttribute(ejbRef, "name", "EjbRef");
        if ejbRefName == None or len(ejbRefName) == 0:
          ejbRefName = ("EjbRef%s" % i)
        Util.addAllFromExport(extraObjects, EjbRef._export(ejbRef, currespath, ejbRefName));
      elif ejbRef.find("#EJBLocalRef_") > 0:
        ejbRefName = Util.getOptionalAttribute(ejbRef, "name", "EJBLocalRef");
        if ejbRefName == None or len(ejbRefName) == 0:
          ejbRefName = ("EJBLocalRef%s" % i)
        Util.addAllFromExport(extraObjects, EJBLocalRef._export(ejbRef, currespath, ejbRefName));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "largeIcon", roleProperties.optString("websphere.jndienvrefsgroup.largeicon", None));
  Util.addIfNotNone(properties, "displayName", roleProperties.optString("websphere.jndienvrefsgroup.displayname", None));
  Util.addIfNotNone(properties, "smallIcon", roleProperties.optString("websphere.jndienvrefsgroup.smallicon", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.jndienvrefsgroup.description", None));
  print "Creating JNDIEnvRefsGroup with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("JNDIEnvRefsGroup", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('PostConstruct')) > -1):
        attName = 'postConstruct';
      elif (foldername.find(Util.getTypeFoldername('PreDestroy')) > -1):
        attName = 'preDestroy';
      elif (foldername.find(Util.getTypeFoldername('EjbRef')) > -1):
        attName = 'ejbRefs';
      elif (foldername.find(Util.getTypeFoldername('EJBLocalRef')) > -1):
        attName = 'ejbLocalRefs';

      if currole == "WebSphereDescription":
        Description.create(objid, curjsonobject);
      elif currole == "WebSphereDisplayName":
        DisplayName.create(objid, curjsonobject);
      elif currole == "WebSphereIconType":
        IconType.create(objid, curjsonobject);
      elif currole == "WebSphereDataSourceDefinition":
        DataSourceDefinition.create(objid, curjsonobject);
      elif currole == "WebSphereEnvEntry":
        EnvEntry.create(objid, curjsonobject);
      elif currole == "WebSphereMessageDestinationRef":
        MessageDestinationRef.create(objid, curjsonobject);
      elif currole == "WebSpherePersistenceContextRef":
        PersistenceContextRef.create(objid, curjsonobject);
      elif currole == "WebSpherePersistenceUnitRef":
        PersistenceUnitRef.create(objid, curjsonobject);
      elif currole == "WebSphereResourceEnvRef":
        ResourceEnvRef.create(objid, curjsonobject);
      elif currole == "WebSphereResourceRef":
        ResourceRef.create(objid, curjsonobject);
      elif currole == "WebSphereLifecycleCallbackType":
        LifecycleCallbackType.create(objid, curjsonobject, attName);
      elif currole == "WebSphereEjbRef":
        EjbRef.create(objid, curjsonobject, attName);
      elif currole == "WebSphereEJBLocalRef":
        EJBLocalRef.create(objid, curjsonobject, attName);
  Util.popPathElement('JNDIEnvRefsGroup');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jndienvrefsgroup.largeicon", None), "largeIcon","JNDIEnvRefsGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jndienvrefsgroup.displayname", None), "displayName","JNDIEnvRefsGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jndienvrefsgroup.smallicon", None), "smallIcon","JNDIEnvRefsGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jndienvrefsgroup.description", None), "description","JNDIEnvRefsGroup");
  if len(atts) != 0:
    print "Modifying JNDIEnvRefsGroup with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  descriptions = Util.parseConfigIdListAttribute(objid, 'descriptions', 'JNDIEnvRefsGroup');
  for description in descriptions:
    if len(description) > 0:
      Util.remove(description);

  displayNames = Util.parseConfigIdListAttribute(objid, 'displayNames', 'JNDIEnvRefsGroup');
  for displayName in displayNames:
    if len(displayName) > 0:
      Util.remove(displayName);

  icons = Util.parseConfigIdListAttribute(objid, 'icons', 'JNDIEnvRefsGroup');
  for icon in icons:
    if len(icon) > 0:
      Util.remove(icon);

  dataSources = Util.parseConfigIdListAttribute(objid, 'dataSources', 'JNDIEnvRefsGroup');
  for dataSource in dataSources:
    if len(dataSource) > 0:
      Util.remove(dataSource);

  environmentProperties = Util.parseConfigIdListAttribute(objid, 'environmentProperties', 'JNDIEnvRefsGroup');
  for environmentProperty in environmentProperties:
    if len(environmentProperty) > 0:
      Util.remove(environmentProperty);

  messageDestinationRefs = Util.parseConfigIdListAttribute(objid, 'messageDestinationRefs', 'JNDIEnvRefsGroup');
  for messageDestinationRef in messageDestinationRefs:
    if len(messageDestinationRef) > 0:
      Util.remove(messageDestinationRef);

  persistenceContextRefs = Util.parseConfigIdListAttribute(objid, 'persistenceContextRefs', 'JNDIEnvRefsGroup');
  for persistenceContextRef in persistenceContextRefs:
    if len(persistenceContextRef) > 0:
      Util.remove(persistenceContextRef);

  persistenceUnitRefs = Util.parseConfigIdListAttribute(objid, 'persistenceUnitRefs', 'JNDIEnvRefsGroup');
  for persistenceUnitRef in persistenceUnitRefs:
    if len(persistenceUnitRef) > 0:
      Util.remove(persistenceUnitRef);

  resourceEnvRefs = Util.parseConfigIdListAttribute(objid, 'resourceEnvRefs', 'JNDIEnvRefsGroup');
  for resourceEnvRef in resourceEnvRefs:
    if len(resourceEnvRef) > 0:
      Util.remove(resourceEnvRef);

  resourceRefs = Util.parseConfigIdListAttribute(objid, 'resourceRefs', 'JNDIEnvRefsGroup');
  for resourceRef in resourceRefs:
    if len(resourceRef) > 0:
      Util.remove(resourceRef);

  postConstructs = Util.parseConfigIdListAttribute(objid, 'postConstruct', 'JNDIEnvRefsGroup');
  for postConstruct in postConstructs:
    if len(postConstruct) > 0:
      Util.remove(postConstruct);

  preDestroys = Util.parseConfigIdListAttribute(objid, 'preDestroy', 'JNDIEnvRefsGroup');
  for preDestroy in preDestroys:
    if len(preDestroy) > 0:
      Util.remove(preDestroy);

  ejbLocalRefs = Util.parseConfigIdListAttribute(objid, 'ejbLocalRefs', 'JNDIEnvRefsGroup');
  for ejbLocalRef in ejbLocalRefs:
    if len(ejbLocalRef) > 0:
      Util.remove(ejbLocalRef);

  ejbRefs = Util.parseConfigIdListAttribute(objid, 'ejbRefs', 'JNDIEnvRefsGroup');
  for ejbRef in ejbRefs:
    if len(ejbRef) > 0:
      Util.remove(ejbRef);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('PostConstruct')) > -1):
        attName = 'postConstruct';
      elif (foldername.find(Util.getTypeFoldername('PreDestroy')) > -1):
        attName = 'preDestroy';
      elif (foldername.find(Util.getTypeFoldername('EjbRef')) > -1):
        attName = 'ejbRefs';
      elif (foldername.find(Util.getTypeFoldername('EJBLocalRef')) > -1):
        attName = 'ejbLocalRefs';

      if currole == "WebSphereDescription":
        Description.create(objid, curjsonobject);
      elif currole == "WebSphereDisplayName":
        DisplayName.create(objid, curjsonobject);
      elif currole == "WebSphereIconType":
        IconType.create(objid, curjsonobject);
      elif currole == "WebSphereDataSourceDefinition":
        DataSourceDefinition.create(objid, curjsonobject);
      elif currole == "WebSphereEnvEntry":
        EnvEntry.create(objid, curjsonobject);
      elif currole == "WebSphereMessageDestinationRef":
        MessageDestinationRef.create(objid, curjsonobject);
      elif currole == "WebSpherePersistenceContextRef":
        PersistenceContextRef.create(objid, curjsonobject);
      elif currole == "WebSpherePersistenceUnitRef":
        PersistenceUnitRef.create(objid, curjsonobject);
      elif currole == "WebSphereResourceEnvRef":
        ResourceEnvRef.create(objid, curjsonobject);
      elif currole == "WebSphereResourceRef":
        ResourceRef.create(objid, curjsonobject);
      elif currole == "WebSphereLifecycleCallbackType":
        LifecycleCallbackType.create(objid, curjsonobject, attName);
      elif currole == "WebSphereLifecycleCallbackType":
        LifecycleCallbackType.create(objid, curjsonobject, attName);
      elif currole == "WebSphereEjbRef":
        EjbRef.create(objid, curjsonobject, attName);
      elif currole == "WebSphereEJBLocalRef":
        EJBLocalRef.create(objid, curjsonobject, attName);
  Util.popPathElement('JNDIEnvRefsGroup');
