from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from MatchCriteria import MatchCriteria 
from Property import Property
from utilities import Util

__name_att__ = "websphere.allactivepolicy.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.allactivepolicy.quorumenabled", objid, "quorumEnabled","AllActivePolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.allactivepolicy.isaliveperiodsec", objid, "isAlivePeriodSec","AllActivePolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.allactivepolicy.policyfactory", objid, "policyFactory","AllActivePolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.allactivepolicy.name", objid, "name","AllActivePolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.allactivepolicy.description", objid, "description","AllActivePolicy");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  first = 0;
  typeFolders = {};
  matchcriterias = Util.parseConfigIdListAttribute(objid, 'MatchCriteria',"AllActivePolicy");
  for criteria in matchcriterias:
    returndict = Util.createTypeFolder(respath, "MatchCriteria", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, MatchCriteria._export(criteria, currespath));
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'customProperties',"AllActivePolicy");

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "quorumEnabled", roleProperties.optString("websphere.allactivepolicy.quorumenabled", None));
  Util.addIfNotNone(properties, "isAlivePeriodSec", roleProperties.optString("websphere.allactivepolicy.isaliveperiodsec", None));
  Util.addIfNotNone(properties, "policyFactory", roleProperties.optString("websphere.allactivepolicy.policyfactory", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.allactivepolicy.name", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.allactivepolicy.description", None));
  print "Creating AllActivePolicy with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("AllActivePolicy", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereMatchCriteria":
          MatchCriteria.create(objid, curjsonobject);
  Util.popPathElement('AllActivePolicy');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.allactivepolicy.quorumenabled", None), "quorumEnabled","AllActivePolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.allactivepolicy.isaliveperiodsec", None), "isAlivePeriodSec","AllActivePolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.allactivepolicy.policyfactory", None), "policyFactory","AllActivePolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.allactivepolicy.name", None), "name","AllActivePolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.allactivepolicy.description", None), "description","AllActivePolicy");
  if len(atts) != 0:
    print "Modifying AllActivePolicy with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.modify(objid, [['MatchCriteria','']]);
  
  Property.removeProperties(objid, 'customProperties',"AllActivePolicy");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereMatchCriteria":
          MatchCriteria.create(objid, curjsonobject);

  Util.popPathElement('AllActivePolicy');
