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

__name_att__ = None;

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

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.pmimodule.modulename", objid, "moduleName","PMIModule");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.pmimodule.enable", objid, "enable","PMIModule");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.pmimodule.type", objid, "type","PMIModule");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  subPMIModules = Util.parseConfigIdListAttribute(objid, 'pmimodules',"PMIModule");
  for subPMIModule in subPMIModules:
    if len(subPMIModule) > 0:
      returndict = Util.createTypeFolder(respath, "PMIModule", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      pmiModuleName = Util.getOptionalAttribute(subPMIModule, "moduleName", "PMIModule");
      if pmiModuleName == None or len(pmiModuleName) == 0:
        pmiModuleName = ("PMI Module%s" % i)
      Util.addAllFromExport(extraObjects, _export(subPMIModule, currespath, pmiModuleName));
      i = i + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "moduleName", roleProperties.optString("websphere.pmimodule.modulename", None));
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.pmimodule.enable", None));
  Util.addIfNotNone(properties, "type", roleProperties.optString("websphere.pmimodule.type", None));
  print "Creating PMIModule with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("PMIModule", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSpherePMIModule":
        create(objid, curjsonobject);
  Util.popPathElement('PMIModule');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.pmimodule.modulename", None), "moduleName","PMIModule");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.pmimodule.enable", None), "enable","PMIModule");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.pmimodule.type", None), "type","PMIModule");
  if len(atts) != 0:
    print "Modifying PMIModule with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  subPMIModules = Util.parseConfigIdListAttribute(objid, 'pmimodules', "PMIModule");
  for subPMIModule in subPMIModules:
    if len(subPMIModule) > 0:
      Util.remove(subPMIModule);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSpherePMIModule":
        create(objid, curjsonobject);
  Util.popPathElement('PMIModule');

def getTopPMIModule(objid):
  topPMIModule = Util.getAssociatedObjects(objid, "PMIModule");
  return topPMIModule;
