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

__name_att__ = "websphere.cacheinstance.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.diskcacheentrysizeinmb", objid, "diskCacheEntrySizeInMB","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.defaultpriority", objid, "defaultPriority","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.uselistenercontext", objid, "useListenerContext","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.pushfrequency", objid, "pushFrequency","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.memorycachesizeinmb", objid, "memoryCacheSizeInMB","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.hashsize", objid, "hashSize","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.providertype", objid, "providerType","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.diskcachesizeinentries", objid, "diskCacheSizeInEntries","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.diskoffloadlocation", objid, "diskOffloadLocation","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.diskcachesizeingb", objid, "diskCacheSizeInGB","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.enablecachereplication", objid, "enableCacheReplication","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.cachesize", objid, "cacheSize","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.jndiname", objid, "jndiName","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.enablediskoffload", objid, "enableDiskOffload","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.replicationtype", objid, "replicationType","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.category", objid, "category","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.description", objid, "description","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.diskcachecleanupfrequency", objid, "diskCacheCleanupFrequency","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.flushtodiskonstop", objid, "flushToDiskOnStop","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.diskcacheperformancelevel", objid, "diskCachePerformanceLevel","CacheInstance");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheinstance.name", objid, "name","CacheInstance");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  
  typeFolders = {};
  drsSettings = Util.getOptionalAttribute(objid, 'cacheReplication',"CacheInstance");
  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('CacheInstance');
  return result;



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  return objid;        


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

    Util.modify(objid, atts);
  else:   
    print "CacheInstance configuration up to date.";
    
  drsSettings = Util.getOptionalAttribute(objid, 'cacheReplication',"CacheInstance");
  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('CacheInstance');
