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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.defaultvirtualhostname", objid, "defaultVirtualHostName","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.allowasyncrequestdispatching", objid, "allowAsyncRequestDispatching","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.disablepooling", objid, "disablePooling","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.maximumpercentageexpiredentries", objid, "maximumPercentageExpiredEntries","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.asyncrunnableworkmanager", objid, "asyncRunnableWorkManager","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.defaultasyncservlettimeout", objid, "defaultAsyncServletTimeout","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.sessionaffinitytimeout", objid, "sessionAffinityTimeout","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.asyncincludetimeout", objid, "asyncIncludeTimeout","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.maximumresponsestoresize", objid, "maximumResponseStoreSize","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.numberasynctimerthreads", objid, "numberAsyncTimerThreads","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.sessionaffinityfailoverserver", objid, "sessionAffinityFailoverServer","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.enableservletcaching", objid, "enableServletCaching","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.useasyncrunnableworkmanager", objid, "useAsyncRunnableWorkManager","WebContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.webcontainer.name", objid, "name","WebContainer");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"WebContainer");
  extraObjects = Component.exportComponents(objid, respath, extraObjects, typeFolders, 'components', "WebContainer");
  extraObjects = Service.exportServices(objid, respath, extraObjects, typeFolders, 'services', "WebContainer");

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

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"WebContainer");
  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"));      
    
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('WebContainer');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "defaultVirtualHostName", roleProperties.optString("websphere.webcontainer.defaultvirtualhostname", None));
  Util.addIfNotNone(properties, "allowAsyncRequestDispatching", roleProperties.optString("websphere.webcontainer.allowasyncrequestdispatching", None));
  Util.addIfNotNone(properties, "disablePooling", roleProperties.optString("websphere.webcontainer.disablepooling", None));
  Util.addIfNotNone(properties, "maximumPercentageExpiredEntries", roleProperties.optString("websphere.webcontainer.maximumpercentageexpiredentries", None));
  Util.addIfNotNone(properties, "asyncRunnableWorkManager", roleProperties.optString("websphere.webcontainer.asyncrunnableworkmanager", None));
  Util.addIfNotNone(properties, "defaultAsyncServletTimeout", roleProperties.optString("websphere.webcontainer.defaultasyncservlettimeout", None));
  Util.addIfNotNone(properties, "sessionAffinityTimeout", roleProperties.optString("websphere.webcontainer.sessionaffinitytimeout", None));
  Util.addIfNotNone(properties, "asyncIncludeTimeout", roleProperties.optString("websphere.webcontainer.asyncincludetimeout", None));
  Util.addIfNotNone(properties, "maximumResponseStoreSize", roleProperties.optString("websphere.webcontainer.maximumresponsestoresize", None));
  Util.addIfNotNone(properties, "numberAsyncTimerThreads", roleProperties.optString("websphere.webcontainer.numberasynctimerthreads", None));
  Util.addIfNotNone(properties, "sessionAffinityFailoverServer", roleProperties.optString("websphere.webcontainer.sessionaffinityfailoverserver", None));
  Util.addIfNotNone(properties, "enableServletCaching", roleProperties.optString("websphere.webcontainer.enableservletcaching", None));
  Util.addIfNotNone(properties, "useAsyncRunnableWorkManager", roleProperties.optString("websphere.webcontainer.useasyncrunnableworkmanager", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.webcontainer.name", None));
  print "Creating WebContainer with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("WebContainer", parentid, properties);

  Property.removeProperties(objid, 'properties',"WebContainer");
  Component.removeComponents(objid, 'components', "WebContainer");
  Service.removeServices(objid, 'services', "WebContainer");

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

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"WebContainer");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);        
    
  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 == "WebSphereThreadPool":
            ThreadPool.create(objid, curjsonobject);
          elif currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);            
  Util.popPathElement('WebContainer');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.defaultvirtualhostname", None), "defaultVirtualHostName","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.allowasyncrequestdispatching", None), "allowAsyncRequestDispatching","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.disablepooling", None), "disablePooling","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.maximumpercentageexpiredentries", None), "maximumPercentageExpiredEntries","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.asyncrunnableworkmanager", None), "asyncRunnableWorkManager","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.defaultasyncservlettimeout", None), "defaultAsyncServletTimeout","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.sessionaffinitytimeout", None), "sessionAffinityTimeout","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.asyncincludetimeout", None), "asyncIncludeTimeout","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.maximumresponsestoresize", None), "maximumResponseStoreSize","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.numberasynctimerthreads", None), "numberAsyncTimerThreads","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.sessionaffinityfailoverserver", None), "sessionAffinityFailoverServer","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.enableservletcaching", None), "enableServletCaching","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.useasyncrunnableworkmanager", None), "useAsyncRunnableWorkManager","WebContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.webcontainer.name", None), "name","WebContainer");
  if len(atts) != 0:
    print "Modifying WebContainer with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"WebContainer");
  Component.removeComponents(objid, 'components', "WebContainer");
  Service.removeServices(objid, 'services', "WebContainer");

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

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"WebContainer");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);         
    
  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 == "WebSphereThreadPool":
            ThreadPool.create(objid, curjsonobject);
          elif currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);            
  Util.popPathElement('WebContainer');
