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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.usingmultirowschema", objid, "usingMultiRowSchema","TuningParams");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.invalidationtimeout", objid, "invalidationTimeout","TuningParams");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.allowoverflow", objid, "allowOverflow","TuningParams");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.writeinterval", objid, "writeInterval","TuningParams");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.writefrequency", objid, "writeFrequency","TuningParams");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.writecontents", objid, "writeContents","TuningParams");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.scheduleinvalidation", objid, "scheduleInvalidation","TuningParams");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tuningparams.maxinmemorysessioncount", objid, "maxInMemorySessionCount","TuningParams");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  invalidationSchedule = Util.getOptionalAttribute(objid, 'invalidationSchedule', 'TuningParams');
  if invalidationSchedule is not None and len(invalidationSchedule) > 0:
    returndict = Util.createTypeFolder(respath, "InvalidationSchedule", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, InvalidationSchedule._export(invalidationSchedule, currespath, 'InvalidationSchedule'));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "usingMultiRowSchema", roleProperties.optString("websphere.tuningparams.usingmultirowschema", None));
  Util.addIfNotNone(properties, "invalidationTimeout", roleProperties.optString("websphere.tuningparams.invalidationtimeout", None));
  Util.addIfNotNone(properties, "allowOverflow", roleProperties.optString("websphere.tuningparams.allowoverflow", None));
  Util.addIfNotNone(properties, "writeInterval", roleProperties.optString("websphere.tuningparams.writeinterval", None));
  Util.addIfNotNone(properties, "writeFrequency", roleProperties.optString("websphere.tuningparams.writefrequency", None));
  Util.addIfNotNone(properties, "writeContents", roleProperties.optString("websphere.tuningparams.writecontents", None));
  Util.addIfNotNone(properties, "scheduleInvalidation", roleProperties.optString("websphere.tuningparams.scheduleinvalidation", None));
  Util.addIfNotNone(properties, "maxInMemorySessionCount", roleProperties.optString("websphere.tuningparams.maxinmemorysessioncount", None));
  print "Creating TuningParams with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("TuningParams", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereInvalidationSchedule":
        InvalidationSchedule.create(objid, curjsonobject);
  Util.popPathElement('TuningParams');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.usingmultirowschema", None), "usingMultiRowSchema","TuningParams");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.invalidationtimeout", None), "invalidationTimeout","TuningParams");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.allowoverflow", None), "allowOverflow","TuningParams");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.writeinterval", None), "writeInterval","TuningParams");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.writefrequency", None), "writeFrequency","TuningParams");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.writecontents", None), "writeContents","TuningParams");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.scheduleinvalidation", None), "scheduleInvalidation","TuningParams");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tuningparams.maxinmemorysessioncount", None), "maxInMemorySessionCount","TuningParams");
  if len(atts) != 0:
    print "Modifying TuningParams with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereInvalidationSchedule":
        InvalidationSchedule.update(objid, curjsonobject);

  Util.popPathElement('TuningParams');
