from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from ExternalCacheGroup import ExternalCacheGroup
from DRSSettings import DRSSettings
from DiskCacheCustomPerformanceSettings import DiskCacheCustomPerformanceSettings
from DiskCacheEvictionPolicy import DiskCacheEvictionPolicy
from MemoryCacheEvictionPolicy import MemoryCacheEvictionPolicy
from utilities import Util
from Property import Property

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.diskcacheentrysizeinmb", objid, "diskCacheEntrySizeInMB","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.defaultpriority", objid, "defaultPriority","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.pushfrequency", objid, "pushFrequency","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.memorycachesizeinmb", objid, "memoryCacheSizeInMB","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.hashsize", objid, "hashSize","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.diskcachesizeinentries", objid, "diskCacheSizeInEntries","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.diskoffloadlocation", objid, "diskOffloadLocation","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.cacheprovider", objid, "cacheProvider","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.diskcachesizeingb", objid, "diskCacheSizeInGB","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.enable", objid, "enable","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.enablecachereplication", objid, "enableCacheReplication","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.cachesize", objid, "cacheSize","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.enablediskoffload", objid, "enableDiskOffload","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.replicationtype", objid, "replicationType","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.enabletaglevelcaching", objid, "enableTagLevelCaching","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.diskcachecleanupfrequency", objid, "diskCacheCleanupFrequency","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.flushtodiskonstop", objid, "flushToDiskOnStop","DynamicCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.dynamiccache.diskcacheperformancelevel", objid, "diskCachePerformanceLevel","DynamicCache");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"DynamicCache");

  i = 0;
  cacheGroups = Util.parseConfigIdListAttribute(objid, 'cacheGroups',"DynamicCache");
  for cacheGroup in cacheGroups:
    if len(cacheGroup) > 0:
      returndict = Util.createTypeFolder(respath, "ExternalCacheGroup", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ExternalCacheGroup._export(cacheGroup, currespath, "ExternalCacheGroup%s" % i));
      i = i + 1;

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

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

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "diskCacheEntrySizeInMB", roleProperties.optString("websphere.dynamiccache.diskcacheentrysizeinmb", None));
  Util.addIfNotNone(properties, "defaultPriority", roleProperties.optString("websphere.dynamiccache.defaultpriority", None));
  Util.addIfNotNone(properties, "pushFrequency", roleProperties.optString("websphere.dynamiccache.pushfrequency", None));
  Util.addIfNotNone(properties, "memoryCacheSizeInMB", roleProperties.optString("websphere.dynamiccache.memorycachesizeinmb", None));
  Util.addIfNotNone(properties, "hashSize", roleProperties.optString("websphere.dynamiccache.hashsize", None));
  Util.addIfNotNone(properties, "diskCacheSizeInEntries", roleProperties.optString("websphere.dynamiccache.diskcachesizeinentries", None));
  Util.addIfNotNone(properties, "diskOffloadLocation", roleProperties.optString("websphere.dynamiccache.diskoffloadlocation", None));
  Util.addIfNotNone(properties, "cacheProvider", roleProperties.optString("websphere.dynamiccache.cacheprovider", None));
  Util.addIfNotNone(properties, "diskCacheSizeInGB", roleProperties.optString("websphere.dynamiccache.diskcachesizeingb", None));
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.dynamiccache.enable", None));
  Util.addIfNotNone(properties, "enableCacheReplication", roleProperties.optString("websphere.dynamiccache.enablecachereplication", None));
  Util.addIfNotNone(properties, "cacheSize", roleProperties.optString("websphere.dynamiccache.cachesize", None));
  Util.addIfNotNone(properties, "enableDiskOffload", roleProperties.optString("websphere.dynamiccache.enablediskoffload", None));
  Util.addIfNotNone(properties, "replicationType", roleProperties.optString("websphere.dynamiccache.replicationtype", None));
  Util.addIfNotNone(properties, "enableTagLevelCaching", roleProperties.optString("websphere.dynamiccache.enabletaglevelcaching", None));
  Util.addIfNotNone(properties, "diskCacheCleanupFrequency", roleProperties.optString("websphere.dynamiccache.diskcachecleanupfrequency", None));
  Util.addIfNotNone(properties, "flushToDiskOnStop", roleProperties.optString("websphere.dynamiccache.flushtodiskonstop", None));
  Util.addIfNotNone(properties, "diskCachePerformanceLevel", roleProperties.optString("websphere.dynamiccache.diskcacheperformancelevel", None));
  print "Creating DynamicCache with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("DynamicCache", 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);
      if (propertyObject == 0):
        if currole == "WebSphereExternalCacheGroup":
          ExternalCacheGroup.create(objid, curjsonobject);
        elif currole == "WebSphereDRSSettings":
          DRSSettings.create(objid, curjsonobject);
        elif currole == "WebSphereDiskCacheCustomPerformanceSettings":
          DiskCacheCustomPerformanceSettings.create(objid, curjsonobject);
        elif currole == "WebSphereDiskCacheEvictionPolicy":
          DiskCacheEvictionPolicy.create(objid, curjsonobject);
        elif currole == "WebSphereMemoryCacheEvictionPolicy":
          MemoryCacheEvictionPolicy.create(objid, curjsonobject);
  Util.popPathElement('DynamicCache');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.diskcacheentrysizeinmb", None), "diskCacheEntrySizeInMB","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.defaultpriority", None), "defaultPriority","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.pushfrequency", None), "pushFrequency","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.memorycachesizeinmb", None), "memoryCacheSizeInMB","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.hashsize", None), "hashSize","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.diskcachesizeinentries", None), "diskCacheSizeInEntries","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.diskoffloadlocation", None), "diskOffloadLocation","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.cacheprovider", None), "cacheProvider","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.diskcachesizeingb", None), "diskCacheSizeInGB","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.enable", None), "enable","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.enablecachereplication", None), "enableCacheReplication","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.cachesize", None), "cacheSize","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.enablediskoffload", None), "enableDiskOffload","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.replicationtype", None), "replicationType","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.enabletaglevelcaching", None), "enableTagLevelCaching","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.diskcachecleanupfrequency", None), "diskCacheCleanupFrequency","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.flushtodiskonstop", None), "flushToDiskOnStop","DynamicCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.dynamiccache.diskcacheperformancelevel", None), "diskCachePerformanceLevel","DynamicCache");
  if len(atts) != 0:
    print "Modifying DynamicCache with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"DynamicCache");

  cacheGroups = Util.parseConfigIdListAttribute(objid, 'cacheGroups',"DynamicCache");
  for cacheGroup in cacheGroups:
    if len(cacheGroup) > 0:
      Util.remove(cacheGroup);

  cacheReplication = Util.getOptionalAttribute(objid, 'cacheReplication', 'DynamicCache');
  if cacheReplication is not None and len(cacheReplication) > 0:
    Util.remove(cacheReplication);

  diskCacheCustomPerformanceSettings = Util.getOptionalAttribute(objid, 'diskCacheCustomPerformanceSettings', 'DynamicCache');
  if diskCacheCustomPerformanceSettings is not None and len(diskCacheCustomPerformanceSettings) > 0:
    Util.remove(diskCacheCustomPerformanceSettings);

  diskCacheEvictionPolicy = Util.getOptionalAttribute(objid, 'diskCacheEvictionPolicy', 'DynamicCache');
  if diskCacheEvictionPolicy is not None and len(diskCacheEvictionPolicy) > 0:
    Util.remove(diskCacheEvictionPolicy);

  memoryCacheEvictionPolicy = Util.getOptionalAttribute(objid, 'memoryCacheEvictionPolicy', 'DynamicCache');
  if memoryCacheEvictionPolicy is not None and len(memoryCacheEvictionPolicy) > 0:
    Util.remove(memoryCacheEvictionPolicy);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereExternalCacheGroup":
          ExternalCacheGroup.create(objid, curjsonobject);
        elif currole == "WebSphereDRSSettings":
          DRSSettings.create(objid, curjsonobject);
        elif currole == "WebSphereDiskCacheCustomPerformanceSettings":
          DiskCacheCustomPerformanceSettings.create(objid, curjsonobject);
        elif currole == "WebSphereDiskCacheEvictionPolicy":
          DiskCacheEvictionPolicy.create(objid, curjsonobject);
        elif currole == "WebSphereMemoryCacheEvictionPolicy":
          MemoryCacheEvictionPolicy.create(objid, curjsonobject);
  Util.popPathElement('DynamicCache');
