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

__name_att__ = "websphere.oneofnpolicy.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.oneofnpolicy.name", objid, "name","OneOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.oneofnpolicy.failback", objid, "failback","OneOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.oneofnpolicy.quorumenabled", objid, "quorumEnabled","OneOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.oneofnpolicy.preferredonly", objid, "preferredOnly","OneOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.oneofnpolicy.description", objid, "description","OneOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.oneofnpolicy.policyfactory", objid, "policyFactory","OneOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.oneofnpolicy.isaliveperiodsec", objid, "isAlivePeriodSec","OneOfNPolicy");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  first = 0;
  matchcriterias = Util.parseConfigIdListAttribute(objid, 'MatchCriteria',"OneOfNPolicy");
  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',"OneOfNPolicy");

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.oneofnpolicy.name"):
    raise Exception("Resource role properties does not contain websphere.oneofnpolicy.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 OneOfNPolicy on.");
    objid = create(parentid, jsonobject);
  else:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    update(objid,jsonobject, parentid);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  coreGroupServers = Util.parseConfigIdListAttribute(parentid, 'coreGroupServers',"OneOfNPolicy");
  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 == "WebSphereCoreGroupServerRef":
          CoreGroupServerRef.create(objid, curjsonobject, 'preferredServers', coreGroupServers);
        elif currole == "WebSphereMatchCriteria":
          MatchCriteria.create(objid, curjsonobject);
  Util.popPathElement('OneOfNPolicy');
  return objid;


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  #only reset servers if there is a coregroupserverref in the handletypepaths under this thingy.
  if Util.hasTypePathForTypeUnderCurrent('CoreGroupServerRef'):
    Util.modify(objid, [['preferredServers','']]);
  else:
    Log.debug("Not resetting preferredServers on OneOfMPolicy because no CoreGroupServerRefs in handle type paths");
  Util.modify(objid, [['MatchCriteria', '']]);

  Property.removeProperties(objid, 'customProperties',"OneOfNPolicy");

  coreGroupServers = None;
  if parentid is not None and len(parentid) > 0:
    #the parent of policies has to be a CoreGroup
    coreGroupServers = Util.parseConfigIdListAttribute(parentid, 'coreGroupServers',"CoreGroup");
  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 == "WebSphereCoreGroupServerRef":
          CoreGroupServerRef.create(objid, curjsonobject, 'preferredServers', coreGroupServers);
        elif currole == "WebSphereMatchCriteria":
          MatchCriteria.create(objid, curjsonobject);

  Util.popPathElement('OneOfNPolicy');
