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

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('HealthController')


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.healthcontroller.controlcyclelength", objid, "controlCycleLength","HealthController");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.healthcontroller.maxconsecutiverestarts", objid, "maxConsecutiveRestarts","HealthController");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.healthcontroller.minrestartintervalunits", objid, "minRestartIntervalUnits","HealthController");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.healthcontroller.enable", objid, "enable","HealthController");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.healthcontroller.restarttimeout", objid, "restartTimeout","HealthController");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.healthcontroller.minrestartinterval", objid, "minRestartInterval","HealthController");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"HealthController");

  i = 0;
  prohibitedRestartTimes = Util.parseConfigIdListAttribute(objid, 'prohibitedRestartTimes',"HealthController");
  for prohibitedRestartTime in prohibitedRestartTimes:
    if len(prohibitedRestartTime) > 0:
      returndict = Util.createTypeFolder(respath, "RestartTime", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, RestartTime._export(prohibitedRestartTime, currespath, "RestartTime%s" % i));
      i = i + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "controlCycleLength", roleProperties.optString("websphere.healthcontroller.controlcyclelength", None));
  Util.addIfNotNone(properties, "maxConsecutiveRestarts", roleProperties.optString("websphere.healthcontroller.maxconsecutiverestarts", None));
  Util.addIfNotNone(properties, "minRestartIntervalUnits", roleProperties.optString("websphere.healthcontroller.minrestartintervalunits", None));
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.healthcontroller.enable", None));
  Util.addIfNotNone(properties, "restartTimeout", roleProperties.optString("websphere.healthcontroller.restarttimeout", None));
  Util.addIfNotNone(properties, "minRestartInterval", roleProperties.optString("websphere.healthcontroller.minrestartinterval", None));
  print "Creating HealthController with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("HealthController", parentid, properties);

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.healthcontroller.controlcyclelength", None), "controlCycleLength","HealthController");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.healthcontroller.maxconsecutiverestarts", None), "maxConsecutiveRestarts","HealthController");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.healthcontroller.minrestartintervalunits", None), "minRestartIntervalUnits","HealthController");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.healthcontroller.enable", None), "enable","HealthController");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.healthcontroller.restarttimeout", None), "restartTimeout","HealthController");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.healthcontroller.minrestartinterval", None), "minRestartInterval","HealthController");
  if len(atts) != 0:
    print "Modifying HealthController with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"HealthController");

  prohibitedRestartTimes = Util.parseConfigIdListAttribute(objid, 'prohibitedRestartTimes',"HealthController");
  for prohibitedRestartTime in prohibitedRestartTimes:
    if len(prohibitedRestartTime) > 0:
      Util.remove(prohibitedRestartTime);

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