from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Service import Service
from Component import Component
from Property import Property
from utilities import Util
from EJBAsync import EJBAsync
from EJBCache import EJBCache
from DRSSettings import DRSSettings
from EJBTimer import EJBTimer
from StateManageable import StateManageable

__name_att__ = None;

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

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbcontainer.name", objid, "name","EJBContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbcontainer.enablesfsbfailover", objid, "enableSFSBFailover","EJBContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbcontainer.passivationdirectory", objid, "passivationDirectory","EJBContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbcontainer.defaultdatasourcejndiname", objid, "defaultDatasourceJNDIName","EJBContainer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ejbcontainer.inactivepoolcleanupinterval", objid, "inactivePoolCleanupInterval","EJBContainer");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"EJBContainer");
  extraObjects = Component.exportComponents(objid, respath, extraObjects, typeFolders, 'components', "EJBContainer");
  extraObjects = Service.exportServices(objid, respath, extraObjects, typeFolders, 'services', "EJBContainer");
  
  ejbAsync = Util.getRequiredAttribute(objid, 'asyncSettings',"EJBContainer");
  if ejbAsync is not None and len(ejbAsync) > 0:
    returndict = Util.createTypeFolder(respath, "EJBAsync", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, EJBAsync._export(ejbAsync, currespath, "EJBAsync")); 
  
  ejbCache = Util.getRequiredAttribute(objid, 'cacheSettings',"EJBContainer");
  if ejbCache is not None and len(ejbCache) > 0:
    returndict = Util.createTypeFolder(respath, "EJBCache", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, EJBCache._export(ejbCache, currespath, "EJBCache")); 
  
  drsSettings = Util.getOptionalAttribute(objid, 'drsSettings',"EJBContainer");
  if drsSettings is not None and len(drsSettings) > 0:
    returndict = Util.createTypeFolder(respath, "DRSSettings", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, DRSSettings._export(drsSettings, currespath, "DRSSettings"));
  
  ejbTimer = Util.getRequiredAttribute(objid, 'timerSettings',"EJBContainer");
  if ejbTimer is not None and len(ejbTimer) > 0:
    returndict = Util.createTypeFolder(respath, "EJBTimer", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, EJBTimer._export(ejbTimer, currespath, "EJBTimer"));  

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"EJBContainer");
  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('EJBContainer');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.ejbcontainer.name", None));
  Util.addIfNotNone(properties, "enableSFSBFailover", roleProperties.optString("websphere.ejbcontainer.enablesfsbfailover", None));
  Util.addIfNotNone(properties, "passivationDirectory", roleProperties.optString("websphere.ejbcontainer.passivationdirectory", None));
  Util.addIfNotNone(properties, "defaultDatasourceJNDIName", roleProperties.optString("websphere.ejbcontainer.defaultdatasourcejndiname", None));
  Util.addIfNotNone(properties, "inactivePoolCleanupInterval", roleProperties.optString("websphere.ejbcontainer.inactivepoolcleanupinterval", None));
  print "Creating EJBContainer with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("EJBContainer", parentid, properties);

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

  ejbAsync = Util.getRequiredAttribute(objid, 'asyncSettings',"EJBContainer");
  if ejbAsync is not None and len(ejbAsync) > 0:
    Util.remove(ejbAsync);
  
  ejbCache = Util.getRequiredAttribute(objid, 'cacheSettings',"EJBContainer");
  if ejbCache is not None and len(ejbCache) > 0:
    Util.remove(ejbCache);
  
  drsSettings = Util.getOptionalAttribute(objid, 'drsSettings',"EJBContainer");
  if drsSettings is not None and len(drsSettings) > 0:
    Util.remove(drsSettings);
  
  ejbTimer = Util.getRequiredAttribute(objid, 'timerSettings',"EJBContainer");
  if ejbTimer is not None and len(ejbTimer) > 0:  
    Util.remove(ejbTimer);

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"EJBContainer");
  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 == "WebSphereEJBAsync":
            EJBAsync.create(objid, curjsonobject);
          elif currole == "WebSphereEJBCache":
            EJBCache.create(objid, curjsonobject);
          elif currole == "WebSphereDRSSettings":
            DRSSettings.create(objid, curjsonobject);           
          elif currole == "WebSphereEJBTimer":
            EJBTimer.create(objid, curjsonobject, 'timerSettings');
          elif currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);            
  Util.popPathElement('EJBContainer');
           

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbcontainer.name", None), "name","EJBContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbcontainer.enablesfsbfailover", None), "enableSFSBFailover","EJBContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbcontainer.passivationdirectory", None), "passivationDirectory","EJBContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbcontainer.defaultdatasourcejndiname", None), "defaultDatasourceJNDIName","EJBContainer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ejbcontainer.inactivepoolcleanupinterval", None), "inactivePoolCleanupInterval","EJBContainer");
  if len(atts) != 0:
    print "Modifying EJBContainer with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  ejbAsync = Util.getRequiredAttribute(objid, 'asyncSettings',"EJBContainer");
  if ejbAsync is not None and len(ejbAsync) > 0:
    Util.remove(ejbAsync);
  
  ejbCache = Util.getRequiredAttribute(objid, 'cacheSettings',"EJBContainer");
  if ejbCache is not None and len(ejbCache) > 0:
    Util.remove(ejbCache);
  
  drsSettings = Util.getOptionalAttribute(objid, 'drsSettings',"EJBContainer");
  if drsSettings is not None and len(drsSettings) > 0:
    Util.remove(drsSettings);
  
  ejbTimer = Util.getRequiredAttribute(objid, 'timerSettings',"EJBContainer");
  if ejbTimer is not None and len(ejbTimer) > 0:  
    Util.remove(ejbTimer);

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"EJBContainer");
  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 == "WebSphereEJBAsync":
            EJBAsync.create(objid, curjsonobject);
          elif currole == "WebSphereEJBCache":
            EJBCache.create(objid, curjsonobject);
          elif currole == "WebSphereDRSSettings":
            DRSSettings.create(objid, curjsonobject);           
          elif currole == "WebSphereEJBTimer":
            EJBTimer.create(objid, curjsonobject, 'timerSettings');
          elif currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);            
  Util.popPathElement('EJBContainer');
