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");

# according to https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/rwve_odhmscript.html
# HealthTime objects cannot be updated with wsadmin (HealthTime is child of RestartTime)
#  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 doImportPartial(containmentpath, roleName, jsonobject):
  return doImport(containmentpath, roleName, jsonobject);

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    if Util.__removePartialConfig__ == "false":
      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 HealthController on.");
      objid = create(parentid, jsonobject, None);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(objid);
      objid = None;
    else:
      update(objid,jsonobject, None);
  return objid;


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);
# according to https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/rwve_odhmscript.html
# HealthTime objects cannot be updated with wsadmin (HealthTime is child of RestartTime)
#      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");

# according to https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/rwve_odhmscript.html
# HealthTime objects cannot be updated with wsadmin (HealthTime is child of RestartTime)
#  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);
# according to https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/rwve_odhmscript.html
# HealthTime objects cannot be updated with wsadmin (HealthTime is child of RestartTime)
#      if (propertyObject == 0):
#        if currole == "WebSphereRestartTime":
#          RestartTime.create(objid, curjsonobject);
  Util.popPathElement('HealthController');
