###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2003, 2016. 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 InjectionTarget import InjectionTarget

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.name", objid, "name","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.indeterminateejbref", objid, "indeterminateEJBRef","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.lookupname", objid, "lookupName","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.remote", objid, "remote","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.type", objid, "type","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.home", objid, "home","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.link", objid, "link","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.description", objid, "description","EjbRef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbref.mappedname", objid, "mappedName","EjbRef");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  descriptions = Util.parseConfigIdListAttribute(objid, 'descriptions', 'EjbRef');
  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;
  injectionTargets = Util.parseConfigIdListAttribute(objid, 'injectionTargets', 'EjbRef');
  for injTarget in injectionTargets:
    if len(injTarget) > 0:
      returndict = Util.createTypeFolder(respath, "InjectionTarget", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      injName = Util.getOptionalAttribute(injTarget, "injectionTargetName", "InjectionTarget");
      if injName is not None and len(injName) > 0:
        resourceName = injName;
      else:
        resourceName = "InjectionTarget%s" % i;
      Util.addAllFromExport(extraObjects, InjectionTarget._export(injTarget, currespath, resourceName));
      i = i + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.ejbref.name", None));
  Util.addIfNotNone(properties, "indeterminateEJBRef", roleProperties.optString("websphere.ejbref.indeterminateejbref", "false"));
  Util.addIfNotNone(properties, "lookupName", roleProperties.optString("websphere.ejbref.lookupname", ""));
  Util.addIfNotNone(properties, "remote", roleProperties.optString("websphere.ejbref.remote", None));
  Util.addIfNotNone(properties, "type", roleProperties.optString("websphere.ejbref.type", None));
  Util.addIfNotNone(properties, "home", roleProperties.optString("websphere.ejbref.home", None));
  Util.addIfNotNone(properties, "link", roleProperties.optString("websphere.ejbref.link", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.ejbref.description", None));
  Util.addIfNotNone(properties, "mappedName", roleProperties.optString("websphere.ejbref.mappedname", None));
  print "Creating EjbRef with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("EjbRef", parentid, properties, attName);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereDescription":
        Description.create(objid, curjsonobject);
      elif currole == "WebSphereInjectionTarget":
        InjectionTarget.create(objid, curjsonobject);
  Util.popPathElement('EjbRef');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.name", None), "name","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.indeterminateejbref", "false"), "indeterminateEJBRef","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.lookupname", ""), "lookupName","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.remote", None), "remote","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.type", None), "type","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.home", None), "home","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.link", None), "link","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.description", None), "description","EjbRef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbref.mappedname", None), "mappedName","EjbRef");
  if len(atts) != 0:
    print "Modifying EjbRef with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  injectionTargets = Util.parseConfigIdListAttribute(objid, 'injectionTargets', 'EjbRef');
  for injTarget in injectionTargets:
    if len(injTarget) > 0:
      Util.remove(injTarget);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereDescription":
        Description.create(objid, curjsonobject);
      elif currole == "WebSphereInjectionTarget":
        InjectionTarget.create(objid, curjsonobject);
  Util.popPathElement('EjbRef');
