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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbcache.cleanupinterval", objid, "cleanupInterval","EJBCache");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbcache.cachesize", objid, "cacheSize","EJBCache");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('EJBCache');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "cleanupInterval", roleProperties.optString("websphere.ejbcache.cleanupinterval", None));
  Util.addIfNotNone(properties, "cacheSize", roleProperties.optString("websphere.ejbcache.cachesize", None));
  print "Creating EJBCache with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("EJBCache", parentid, properties);
  Util.popPathElement('EJBCache');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbcache.cleanupinterval", None), "cleanupInterval","EJBCache");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbcache.cachesize", None), "cacheSize","EJBCache");
  if len(atts) != 0:
    print "Modifying EJBCache with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.popPathElement('EJBCache');
