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.mofnpolicy.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.name", objid, "name","MOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.numactive", objid, "numActive","MOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.failback", objid, "failback","MOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.quorumenabled", objid, "quorumEnabled","MOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.preferredonly", objid, "preferredOnly","MOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.description", objid, "description","MOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.policyfactory", objid, "policyFactory","MOfNPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mofnpolicy.isaliveperiodsec", objid, "isAlivePeriodSec","MOfNPolicy");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  first = 0;
  matchcriterias = Util.parseConfigIdListAttribute(objid, 'MatchCriteria',"MOfNPolicy");
  for criteria in matchcriterias:
    if len(criteria) > 0:
      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',"MOfNPolicy");
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('MOfNPolicy');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.mofnpolicy.name"):
    raise Exception("Resource role properties does not contain websphere.mofnpolicy.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 MOfNPolicy 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('MOfNPolicy')
  if not jsonobject.has("roleProperties"):
    raise Exception("MOfNPolicy resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  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('MOfNPolicy');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  Util.modify(objid, [['MatchCriteria','']]);

  #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 MOfNPolicy because no CoreGroupServerRefs in handle type paths");
  Property.removeProperties(objid, 'customProperties',"MOfNPolicy");

  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('MOfNPolicy');
