from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Service import Service
from Property import Property
from Component import Component
from utilities import Util
from StateManageable import StateManageable
from ThreadPoolRef import ThreadPoolRef
from Stack import Stack

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sipcontainer.statupdaterange", objid, "statUpdateRange","SIPContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sipcontainer.name", objid, "name","SIPContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sipcontainer.maxdispatchqueuesize", objid, "maxDispatchQueueSize","SIPContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sipcontainer.maxmessagerate", objid, "maxMessageRate","SIPContainer");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.sipcontainer.dnsservernames", objid, "dnsServerNames","SIPContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sipcontainer.stataverageperiod", objid, "statAveragePeriod","SIPContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sipcontainer.maxresponsetime", objid, "maxResponseTime","SIPContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sipcontainer.maxappsessions", objid, "maxAppSessions","SIPContainer");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"SIPContainer");
  extraObjects = Component.exportComponents(objid, respath, extraObjects, typeFolders, 'components', "SIPContainer");
  extraObjects = Service.exportServices(objid, respath, extraObjects, typeFolders, 'services', "SIPContainer");

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

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "statUpdateRange", roleProperties.optString("websphere.sipcontainer.statupdaterange", None));
  Util.addIfNotNoneOrEmpty(properties, "name", roleProperties.optString("websphere.sipcontainer.name", None));
  Util.addIfNotNone(properties, "maxDispatchQueueSize", roleProperties.optString("websphere.sipcontainer.maxdispatchqueuesize", None));
  Util.addIfNotNone(properties, "maxMessageRate", roleProperties.optString("websphere.sipcontainer.maxmessagerate", None));
  Util.addPathProperty(properties, "dnsServerNames", roleProperties.optString("websphere.sipcontainer.dnsservernames", None));
  Util.addIfNotNone(properties, "statAveragePeriod", roleProperties.optString("websphere.sipcontainer.stataverageperiod", None));
  Util.addIfNotNone(properties, "maxResponseTime", roleProperties.optString("websphere.sipcontainer.maxresponsetime", None));
  Util.addIfNotNone(properties, "maxAppSessions", roleProperties.optString("websphere.sipcontainer.maxappsessions", None));
  print "Creating SIPContainer with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SIPContainer", parentid, properties);

  Property.removeProperties(objid, 'properties',"SIPContainer");
  Component.removeComponents(objid, 'components', "SIPContainer");
  Service.removeServices(objid, 'services', "SIPContainer");
  
  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"SIPContainer");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);

  stack = Util.getRequiredAttribute(objid, 'stack',"SIPContainer");
  if stack is not None and len(stack) > 0:
    Util.remove(stack);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      serviceObject = Service.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if serviceObject == 1:
        children.remove(curjsonobject);

    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      componentObject = Component.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if (componentObject == 0):
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
        if propertyObject == 0:
          if currole == "WebSphereThreadPoolRef":
            ThreadPoolRef.create(objid, curjsonobject, 'threadPool', threadPoolLookupPath);
          elif currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);
          elif currole == "WebSphereStack":
            Stack.create(objid, curjsonobject);
  Util.popPathElement('SIPContainer');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.statupdaterange", None), "statUpdateRange","SIPContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.name", None), "name","SIPContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.maxdispatchqueuesize", None), "maxDispatchQueueSize","SIPContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.maxmessagerate", None), "maxMessageRate","SIPContainer");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.dnsservernames", None), "dnsServerNames","SIPContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.stataverageperiod", None), "statAveragePeriod","SIPContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.maxresponsetime", None), "maxResponseTime","SIPContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sipcontainer.maxappsessions", None), "maxAppSessions","SIPContainer");
  if len(atts) != 0:
    print "Modifying SIPContainer with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"SIPContainer");
  Component.removeComponents(objid, 'components', "SIPContainer");
  Service.removeServices(objid, 'services', "SIPContainer");
  
  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"SIPContainer");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);

  stack = Util.getRequiredAttribute(objid, 'stack',"SIPContainer");
  if stack is not None and len(stack) > 0:
    Util.remove(stack);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      serviceObject = Service.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if serviceObject == 1:
        children.remove(curjsonobject);

    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      componentObject = Component.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if (componentObject == 0):
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
        if propertyObject == 0:
          if currole == "WebSphereThreadPoolRef":
            ThreadPoolRef.create(objid, curjsonobject, 'threadPool', threadPoolLookupPath);
          elif currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);
          elif currole == "WebSphereStack":
            Stack.create(objid, curjsonobject);
  Util.popPathElement('SIPContainer');
