from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from AdminService import AdminService;
from JobManagerRegistration import JobManagerRegistration;
from ThreadPool import ThreadPool
from utilities import Util
from Property import Property

__name_att__ = "websphere.managednode.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.managednode.name", objid, "name","ManagedNode");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.managednode.pollingenabled", objid, "pollingEnabled","ManagedNode");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"ManagedNode");

  adminService = Util.getOptionalAttribute(objid, 'adminService', 'ManagedNode');
  if adminService is not None and len(adminService) > 0:
    returndict = Util.createTypeFolder(respath, "Admin Service", typeFolders, 1);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, AdminService._export(adminService, currespath, 'Admin Service'));

  i = 0;
  jmrs = Util.parseConfigIdListAttribute(objid, 'jobManagerRegistrations', 'ManagedNode');
  if jmrs is not None and len(jmrs) > 0:
    for jmr in jmrs:
      returndict = Util.createTypeFolder(respath, 'JobManagerRegistration', typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, JobManagerRegistration._export(jmr, currespath, "Job Manager Registration %s" % i));
      i = i + 1;

  threadPool = Util.getOptionalAttribute(objid, 'threadPool', 'ManagedNode');
  if threadPool is not None and len(threadPool) > 0:
    returndict = Util.createTypeFolder(respath, "Thread Pool", typeFolders, 1);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ThreadPool._export(threadPool, currespath));

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.managednode.name", None));
  Util.addIfNotNone(properties, "pollingEnabled", roleProperties.optString("websphere.managednode.pollingenabled", None));
  print "Creating ManagedNode with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ManagedNode", parentid, properties);

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

  jmrs = Util.parseConfigIdListAttribute(objid, 'jobManagerRegistrations', 'ManagedNode');
  if jmrs is not None and len(jmrs) > 0:
    for jmr in jmrs:
      Util.remove(jmr);

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereAdminService":
        adminService = AdminService.create(objid, curjsonobject, None);
      elif currole == "WebSphereJobManagerRegistration":
        jmr = JobManagerRegistration.create(objid, curjsonobject);
      elif currole == "WebSphereThreadPool":
        ThreadPool.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('ManagedNode');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.managednode.name", None), "name","ManagedNode");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.managednode.pollingenabled", None), "pollingEnabled","ManagedNode");
  if len(atts) != 0:
    print "Modifying ManagedNode with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

  jmrs = Util.parseConfigIdListAttribute(objid, 'jobManagerRegistrations', 'ManagedNode');
  if jmrs is not None and len(jmrs) > 0:
    for jmr in jmrs:
      Util.remove(jmr);

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereAdminService":
        adminService = AdminService.create(objid, curjsonobject, None);
      elif currole == "WebSphereJobManagerRegistration":
        jmr = JobManagerRegistration.create(objid, curjsonobject);
      elif currole == "WebSphereThreadPool":
        ThreadPool.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);

  Util.popPathElement('ManagedNode');
