from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from ElasticityAction import ElasticityAction;
from CustomElasticityAction import CustomElasticityAction;
from utilities import Util

__name_att__ = "websphere.elasticityclass.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.elasticityclass.reactionmode", objid, "reactionMode","ElasticityClass");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.elasticityclass.name", objid, "name","ElasticityClass");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.elasticityclass.description", objid, "description","ElasticityClass");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  j = 0;
  actions = Util.parseConfigIdListAttribute(objid, 'ElasticityAction', 'ElasticityClass');
  for action in actions:
    if len(action) > 0:
      returndict = Util.createTypeFolder(respath, "ElasticityAction", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      if action.find("#ElasticityAction_") != -1:
        Util.addAllFromExport(extraObjects, ElasticityAction._export(action, currespath, "ElasticityAction%s" % i));
        i = i + 1;
      elif action.find("#CustomElasticityAction_") != -1:
        Util.addAllFromExport(extraObjects, CustomElasticityAction._export(action, currespath, "CustomElasticityAction%s" % j));
        j = j + 1;
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ElasticityClass');
  return result;



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "reactionMode", roleProperties.optString("websphere.elasticityclass.reactionmode", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.elasticityclass.name", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.elasticityclass.description", None));
  print "Creating ElasticityClass with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ElasticityClass", parentid, properties);

  actions = Util.parseConfigIdListAttribute(objid, 'ElasticityAction', 'ElasticityClass');
  for action in actions:
    Util.remove(action);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereElasticityAction":
        ElasticityAction.create(objid, curjsonobject);
      elif currole == "WebSphereCustomElasticityAction":
        CustomElasticityAction.create(objid, curjsonobject);
  Util.popPathElement('ElasticityClass');

  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  actions = Util.parseConfigIdListAttribute(objid, 'ElasticityAction', 'ElasticityClass');
  for action in actions:
    Util.remove(action);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereElasticityAction":
        ElasticityAction.create(objid, curjsonobject);
      elif currole == "WebSphereCustomElasticityAction":
        CustomElasticityAction.create(objid, curjsonobject);

  Util.popPathElement('ElasticityClass');
