#- 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 ConfigProperty import ConfigProperty
from RequiredConfigPropertyType import RequiredConfigPropertyType

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.activationspec.activationspecclass", objid, "activationSpecClass","ActivationSpec");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  properties = Util.parseConfigIdListAttribute(objid, 'configProperties', 'ActivationSpec');
  for prop in properties:
    if len(prop) > 0:
      returndict = Util.createTypeFolder(respath, "ConfigProperty", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ConfigProperty._export(prop, currespath, "ConfigProperty%s" % i));
      i = i + 1;

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


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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "activationSpecClass", roleProperties.optString("websphere.activationspec.activationspecclass", None));
  print "Creating ActivationSpec with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ActivationSpec", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereConfigProperty":
        ConfigProperty.create(objid, curjsonobject);
      elif currole == "WebSphereRequiredConfigPropertyType":
        RequiredConfigPropertyType.create(objid, curjsonobject);
  Util.popPathElement('ActivationSpec');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.activationspec.activationspecclass", None), "activationSpecClass","ActivationSpec");
  if len(atts) != 0:
    print "Modifying ActivationSpec with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  properties = Util.parseConfigIdListAttribute(objid, 'configProperties', 'ActivationSpec');
  for prop in properties:
    if len(prop) > 0:
      Util.remove(prop);

  requiredProperties = Util.parseConfigIdListAttribute(objid, 'requiredConfigProperties', 'ActivationSpec');
  for rprop in requiredProperties:
    if len(rprop) > 0:
      Util.remove(rprop);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereConfigProperty":
        ConfigProperty.create(objid, curjsonobject);
      elif currole == "WebSphereRequiredConfigPropertyType":
        RequiredConfigPropertyType.create(objid, curjsonobject);

  Util.popPathElement('ActivationSpec');
