from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Property import Property
from Cookie import Cookie
from SessionDatabasePersistence import SessionDatabasePersistence
from DRSSettings import DRSSettings
from TuningParams import TuningParams
from utilities import Util

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.enablesecurityintegration", objid, "enableSecurityIntegration","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.maxwaittime", objid, "maxWaitTime","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.allowserializedsessionaccess", objid, "allowSerializedSessionAccess","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.enableprotocolswitchrewriting", objid, "enableProtocolSwitchRewriting","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.enableurlrewriting", objid, "enableUrlRewriting","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.enable", objid, "enable","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.accesssessionontimeout", objid, "accessSessionOnTimeout","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.enablessltracking", objid, "enableSSLTracking","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.sessionpersistencemode", objid, "sessionPersistenceMode","SessionManager");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sessionmanager.enablecookies", objid, "enableCookies","SessionManager");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"SessionManager");

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

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

  sessionDRSPersistence = Util.getOptionalAttribute(objid, 'sessionDRSPersistence', 'SessionManager');
  if sessionDRSPersistence is not None and len(sessionDRSPersistence) > 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(sessionDRSPersistence, currespath, 'SessionDRSPersistence'));

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "enableSecurityIntegration", roleProperties.optString("websphere.sessionmanager.enablesecurityintegration", None));
  Util.addIfNotNone(properties, "maxWaitTime", roleProperties.optString("websphere.sessionmanager.maxwaittime", None));
  Util.addIfNotNone(properties, "allowSerializedSessionAccess", roleProperties.optString("websphere.sessionmanager.allowserializedsessionaccess", None));
  Util.addIfNotNone(properties, "enableProtocolSwitchRewriting", roleProperties.optString("websphere.sessionmanager.enableprotocolswitchrewriting", None));
  Util.addIfNotNone(properties, "enableUrlRewriting", roleProperties.optString("websphere.sessionmanager.enableurlrewriting", None));
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.sessionmanager.enable", None));
  Util.addIfNotNone(properties, "accessSessionOnTimeout", roleProperties.optString("websphere.sessionmanager.accesssessionontimeout", None));
  Util.addIfNotNone(properties, "enableSSLTracking", roleProperties.optString("websphere.sessionmanager.enablessltracking", None));
  Util.addIfNotNone(properties, "sessionPersistenceMode", roleProperties.optString("websphere.sessionmanager.sessionpersistencemode", None));
  Util.addIfNotNone(properties, "enableCookies", roleProperties.optString("websphere.sessionmanager.enablecookies", None));
  print "Creating SessionManager with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SessionManager", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereCookie":
          Cookie.create(objid, curjsonobject);
        elif currole == "WebSphereSessionDatabasePersistence":
          SessionDatabasePersistence.create(objid, curjsonobject);
        elif currole == "WebSphereDRSSettings":
          DRSSettings.create(objid, curjsonobject);
        elif currole == "WebSphereTuningParams":
          TuningParams.create(objid, curjsonobject);
  Util.popPathElement('SessionManager');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.enablesecurityintegration", None), "enableSecurityIntegration","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.maxwaittime", None), "maxWaitTime","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.allowserializedsessionaccess", None), "allowSerializedSessionAccess","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.enableprotocolswitchrewriting", None), "enableProtocolSwitchRewriting","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.enableurlrewriting", None), "enableUrlRewriting","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.enable", None), "enable","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.accesssessionontimeout", None), "accessSessionOnTimeout","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.enablessltracking", None), "enableSSLTracking","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.sessionpersistencemode", None), "sessionPersistenceMode","SessionManager");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sessionmanager.enablecookies", None), "enableCookies","SessionManager");
  if len(atts) != 0:
    print "Modifying SessionManager with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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


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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereCookie":
          Cookie.update(objid, curjsonobject);
        elif currole == "WebSphereSessionDatabasePersistence":
          SessionDatabasePersistence.update(objid, curjsonobject);
        elif currole == "WebSphereDRSSettings":
          DRSSettings.update(objid, curjsonobject);
        elif currole == "WebSphereTuningParams":
          TuningParams.update(objid, curjsonobject);
  Util.popPathElement('SessionManager');
