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

__name_att__ = "websphere.objectcacheinstance.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sObjectCacheInstance:%(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, name):
  Util.pushPathElement('ObjectCacheInstance')

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.diskcacheentrysizeinmb", objid, "diskCacheEntrySizeInMB","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.defaultpriority", objid, "defaultPriority","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.uselistenercontext", objid, "useListenerContext","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.pushfrequency", objid, "pushFrequency","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.memorycachesizeinmb", objid, "memoryCacheSizeInMB","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.hashsize", objid, "hashSize","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.providertype", objid, "providerType","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.diskcachesizeinentries", objid, "diskCacheSizeInEntries","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.diskoffloadlocation", objid, "diskOffloadLocation","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.diskcachesizeingb", objid, "diskCacheSizeInGB","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.enablecachereplication", objid, "enableCacheReplication","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.cachesize", objid, "cacheSize","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.jndiname", objid, "jndiName","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.enablediskoffload", objid, "enableDiskOffload","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.replicationtype", objid, "replicationType","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.category", objid, "category","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.description", objid, "description","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.disabledependencyid", objid, "disableDependencyId","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.diskcachecleanupfrequency", objid, "diskCacheCleanupFrequency","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.flushtodiskonstop", objid, "flushToDiskOnStop","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.diskcacheperformancelevel", objid, "diskCachePerformanceLevel","ObjectCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.objectcacheinstance.name", objid, "name","ObjectCacheInstance");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  
  typeFolders = {};  
  drsSettings = Util.getOptionalAttribute(objid, 'cacheReplication',"ObjectCacheInstance");
  if drsSettings is not None and len(drsSettings) > 0:
    returndict = Util.createTypeFolder(respath, "Cache Replication", typeFolders, 1);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, DRSSettings._export(drsSettings, currespath, "DRSSettings"));  
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ObjectCacheInstance');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.objectcacheinstance.name"):
    raise Exception("Resource role properties does not contain websphere.objectcacheinstance.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 ObjectCacheInstance on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "diskCacheEntrySizeInMB", roleProperties.optString("websphere.objectcacheinstance.diskcacheentrysizeinmb", None));
  Util.addIfNotNone(properties, "defaultPriority", roleProperties.optString("websphere.objectcacheinstance.defaultpriority", None));
  Util.addIfNotNone(properties, "useListenerContext", roleProperties.optString("websphere.objectcacheinstance.uselistenercontext", None));
  Util.addIfNotNone(properties, "pushFrequency", roleProperties.optString("websphere.objectcacheinstance.pushfrequency", None));
  Util.addIfNotNone(properties, "memoryCacheSizeInMB", roleProperties.optString("websphere.objectcacheinstance.memorycachesizeinmb", None));
  Util.addIfNotNone(properties, "hashSize", roleProperties.optString("websphere.objectcacheinstance.hashsize", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.objectcacheinstance.providertype", None));
  Util.addIfNotNone(properties, "diskCacheSizeInEntries", roleProperties.optString("websphere.objectcacheinstance.diskcachesizeinentries", None));
  Util.addIfNotNone(properties, "diskOffloadLocation", roleProperties.optString("websphere.objectcacheinstance.diskoffloadlocation", None));
  Util.addIfNotNone(properties, "diskCacheSizeInGB", roleProperties.optString("websphere.objectcacheinstance.diskcachesizeingb", None));
  Util.addIfNotNone(properties, "enableCacheReplication", roleProperties.optString("websphere.objectcacheinstance.enablecachereplication", None));
  Util.addIfNotNone(properties, "cacheSize", roleProperties.optString("websphere.objectcacheinstance.cachesize", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.objectcacheinstance.jndiname", None));
  Util.addIfNotNone(properties, "enableDiskOffload", roleProperties.optString("websphere.objectcacheinstance.enablediskoffload", None));
  Util.addIfNotNone(properties, "replicationType", roleProperties.optString("websphere.objectcacheinstance.replicationtype", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.objectcacheinstance.category", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.objectcacheinstance.description", None));
  Util.addIfNotNone(properties, "disableDependencyId", roleProperties.optString("websphere.objectcacheinstance.disabledependencyid", None));
  Util.addIfNotNone(properties, "diskCacheCleanupFrequency", roleProperties.optString("websphere.objectcacheinstance.diskcachecleanupfrequency", None));
  Util.addIfNotNone(properties, "flushToDiskOnStop", roleProperties.optString("websphere.objectcacheinstance.flushtodiskonstop", None));
  Util.addIfNotNone(properties, "diskCachePerformanceLevel", roleProperties.optString("websphere.objectcacheinstance.diskcacheperformancelevel", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.objectcacheinstance.name", None));
  print "Creating ObjectCacheInstance with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ObjectCacheInstance", parentid, properties);
  
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDRSSettings":
        DRSSettings.create(objid, curjsonobject);   
  Util.popPathElement('ObjectCacheInstance');
  
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.diskcacheentrysizeinmb", None), "diskCacheEntrySizeInMB","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.defaultpriority", None), "defaultPriority","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.uselistenercontext", None), "useListenerContext","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.pushfrequency", None), "pushFrequency","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.memorycachesizeinmb", None), "memoryCacheSizeInMB","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.hashsize", None), "hashSize","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.providertype", None), "providerType","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.diskcachesizeinentries", None), "diskCacheSizeInEntries","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.diskoffloadlocation", None), "diskOffloadLocation","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.diskcachesizeingb", None), "diskCacheSizeInGB","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.enablecachereplication", None), "enableCacheReplication","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.cachesize", None), "cacheSize","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.jndiname", None), "jndiName","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.enablediskoffload", None), "enableDiskOffload","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.replicationtype", None), "replicationType","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.category", None), "category","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.description", None), "description","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.disabledependencyid", None), "disableDependencyId","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.diskcachecleanupfrequency", None), "diskCacheCleanupFrequency","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.flushtodiskonstop", None), "flushToDiskOnStop","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.diskcacheperformancelevel", None), "diskCachePerformanceLevel","ObjectCacheInstance");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.objectcacheinstance.name", None), "name","ObjectCacheInstance");
  if len(atts) != 0:
    print "Modifying ObjectCacheInstance with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "ObjectCacheInstance configuration up to date.";
    
  drsSettings = Util.getOptionalAttribute(objid, 'cacheReplication',"ObjectCacheInstance");
  if drsSettings is not None and len(drsSettings) > 0:
    Util.remove(drsSettings);
    
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDRSSettings":
        DRSSettings.create(objid, curjsonobject);           

  Util.popPathElement('ObjectCacheInstance');
