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

__name_att__ = "websphere.servletcacheinstance.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.diskcacheentrysizeinmb", objid, "diskCacheEntrySizeInMB","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.defaultpriority", objid, "defaultPriority","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.uselistenercontext", objid, "useListenerContext","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.pushfrequency", objid, "pushFrequency","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.memorycachesizeinmb", objid, "memoryCacheSizeInMB","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.hashsize", objid, "hashSize","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.providertype", objid, "providerType","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.diskcachesizeinentries", objid, "diskCacheSizeInEntries","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.diskoffloadlocation", objid, "diskOffloadLocation","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.diskcachesizeingb", objid, "diskCacheSizeInGB","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.enablecachereplication", objid, "enableCacheReplication","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.cachesize", objid, "cacheSize","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.jndiname", objid, "jndiName","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.enablediskoffload", objid, "enableDiskOffload","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.replicationtype", objid, "replicationType","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.category", objid, "category","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.description", objid, "description","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.diskcachecleanupfrequency", objid, "diskCacheCleanupFrequency","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.flushtodiskonstop", objid, "flushToDiskOnStop","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.diskcacheperformancelevel", objid, "diskCachePerformanceLevel","ServletCacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servletcacheinstance.name", objid, "name","ServletCacheInstance");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];

  typeFolders = {};  
  drsSettings = Util.getOptionalAttribute(objid, 'cacheReplication',"ServletCacheInstance");
  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('ServletCacheInstance');
  return result;



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "diskCacheEntrySizeInMB", roleProperties.optString("websphere.servletcacheinstance.diskcacheentrysizeinmb", None));
  Util.addIfNotNone(properties, "defaultPriority", roleProperties.optString("websphere.servletcacheinstance.defaultpriority", None));
  Util.addIfNotNone(properties, "useListenerContext", roleProperties.optString("websphere.servletcacheinstance.uselistenercontext", None));
  Util.addIfNotNone(properties, "pushFrequency", roleProperties.optString("websphere.servletcacheinstance.pushfrequency", None));
  Util.addIfNotNone(properties, "memoryCacheSizeInMB", roleProperties.optString("websphere.servletcacheinstance.memorycachesizeinmb", None));
  Util.addIfNotNone(properties, "hashSize", roleProperties.optString("websphere.servletcacheinstance.hashsize", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.servletcacheinstance.providertype", None));
  Util.addIfNotNone(properties, "diskCacheSizeInEntries", roleProperties.optString("websphere.servletcacheinstance.diskcachesizeinentries", None));
  Util.addIfNotNone(properties, "diskOffloadLocation", roleProperties.optString("websphere.servletcacheinstance.diskoffloadlocation", None));
  Util.addIfNotNone(properties, "diskCacheSizeInGB", roleProperties.optString("websphere.servletcacheinstance.diskcachesizeingb", None));
  Util.addIfNotNone(properties, "enableCacheReplication", roleProperties.optString("websphere.servletcacheinstance.enablecachereplication", None));
  Util.addIfNotNone(properties, "cacheSize", roleProperties.optString("websphere.servletcacheinstance.cachesize", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.servletcacheinstance.jndiname", None));
  Util.addIfNotNone(properties, "enableDiskOffload", roleProperties.optString("websphere.servletcacheinstance.enablediskoffload", None));
  Util.addIfNotNone(properties, "replicationType", roleProperties.optString("websphere.servletcacheinstance.replicationtype", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.servletcacheinstance.category", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.servletcacheinstance.description", None));
  Util.addIfNotNone(properties, "diskCacheCleanupFrequency", roleProperties.optString("websphere.servletcacheinstance.diskcachecleanupfrequency", None));
  Util.addIfNotNone(properties, "flushToDiskOnStop", roleProperties.optString("websphere.servletcacheinstance.flushtodiskonstop", None));
  Util.addIfNotNone(properties, "diskCachePerformanceLevel", roleProperties.optString("websphere.servletcacheinstance.diskcacheperformancelevel", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.servletcacheinstance.name", None));
  print "Creating ServletCacheInstance with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ServletCacheInstance", 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('ServletCacheInstance');
  
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  drsSettings = Util.getOptionalAttribute(objid, 'cacheReplication',"ServletCacheInstance");
  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('ServletCacheInstance');
