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

__name_att__ = "websphere.cacheprovider.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sCacheProvider:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath, containmentpath);
  dict['conpath'] = containmentpath;
  return dict

def _export(objid, parentrespath, parentcontainmentpath):
  Util.pushPathElement('CacheProvider')

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


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

  roleProperties = JSONObject();

  Util.addAttributePathPropertyToJson(roleProperties, "websphere.cacheprovider.classpath", objid, "classpath","CacheProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheprovider.name", objid, "name","CacheProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheprovider.isolatedclassloader", objid, "isolatedClassLoader","CacheProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.cacheprovider.nativepath", objid, "nativepath","CacheProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheprovider.description", objid, "description","CacheProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cacheprovider.providertype", objid, "providerType","CacheProvider");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  # get all ObjectCacheInstance objects for this CacheProvider
  objectCacheInstances = Util.getid(parentcontainmentpath + "ObjectCacheInstance:/").splitlines();
  i = 0;
  for objectCacheInstance in objectCacheInstances:
      if len(objectCacheInstance) > 0:
        returndict = Util.createTypeFolder(respath, "ObjectCacheInstance", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, ObjectCacheInstance._export(objectCacheInstance, currespath, "ObjectCacheInstance%s" % i));
        i = i + 1;

  # get all ServletCacheInstance objects for this CacheProvider
  servletCacheInstances = Util.getid(parentcontainmentpath + "ServletCacheInstance:/").splitlines();
  i = 0;
  for servletCacheInstance in servletCacheInstances:
      if len(servletCacheInstance) > 0:
        returndict = Util.createTypeFolder(respath, "ServletCacheInstance", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, ServletCacheInstance._export(servletCacheInstance, currespath, "ServletCacheInstance%s" % i));
        i = i + 1;

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addPathProperty(properties, "classpath", roleProperties.optString("websphere.cacheprovider.classpath", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.cacheprovider.name", None));
  Util.addIfNotNone(properties, "isolatedClassLoader", roleProperties.optString("websphere.cacheprovider.isolatedclassloader", None));
  Util.addPathProperty(properties, "nativepath", roleProperties.optString("websphere.cacheprovider.nativepath", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.cacheprovider.description", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.cacheprovider.providertype", None));
  print "Creating CacheProvider with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("CacheProvider", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereObjectCacheInstance":
        ObjectCacheInstance.create(objid, curjsonobject);
      elif currole == "WebSphereServletCacheInstance":
        ServletCacheInstance.create(objid, curjsonobject);

  Util.popPathElement('CacheProvider');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.cacheprovider.classpath", None), "classpath","CacheProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.cacheprovider.name", None), "name","CacheProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.cacheprovider.isolatedclassloader", None), "isolatedClassLoader","CacheProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.cacheprovider.nativepath", None), "nativepath","CacheProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.cacheprovider.description", None), "description","CacheProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.cacheprovider.providertype", None), "providerType","CacheProvider");
  if len(atts) != 0:
    print "Modifying CacheProvider with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  objectCacheInstances = Util.getid(parentcontainmentpath + "ObjectCacheInstance:/").splitlines();
  if objectCacheInstances != None and len(objectCacheInstances) > 0:
    for objectCacheInstance in objectCacheInstances:
      if len(objectCacheInstance) > 0:
        Util.remove(objectCacheInstance);

  servletCacheInstances = Util.getid(parentcontainmentpath + "ServletCacheInstance:/").splitlines();
  if servletCacheInstances != None and len(servletCacheInstances) > 0:
    for servletCacheInstance in servletCacheInstances:
      if len(servletCacheInstance) > 0:
        Util.remove(servletCacheInstance);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereObjectCacheInstance":
        ObjectCacheInstance.create(objid, curjsonobject);
      elif currole == "WebSphereServletCacheInstance":
        ServletCacheInstance.create(objid, curjsonobject);

  Util.popPathElement('CacheProvider');
