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

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

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

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



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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

    Util.modify(objid, atts);
  else:   
    print "StaticPolicy 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, [['servers','']]);
  else:
    Log.debug("Not resetting servers on StaticPolicy because no CoreGroupServerRefs in handle type paths");
  Property.removeProperties(objid, 'customProperties',"StaticPolicy");

  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, 'servers', coreGroupServers);
        elif currole == "WebSphereMatchCriteria":
          MatchCriteria.create(objid, curjsonobject);

  Util.popPathElement('StaticPolicy');
