from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from DRSSettings import DRSSettings
from SessionManager import SessionManager

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationconfig.enablesfsbfailover", objid, "enableSFSBFailover","ApplicationConfig");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.applicationconfig.overridedefaultdrssettings", objid, "overrideDefaultDRSSettings","ApplicationConfig");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  
  typeFolders = {};
  
  drsSettings = Util.getOptionalAttribute(objid, 'drsSettings',"ApplicationConfig");
  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"));
    
  sessionManager = Util.getRequiredAttribute(objid, 'sessionManagement',"ApplicationConfig");
  if sessionManager is not None and len(sessionManager) > 0:
    returndict = Util.createTypeFolder(respath, "SessionManager", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, SessionManager._export(sessionManager, currespath, "SessionManager"));   
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ApplicationConfig');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "enableSFSBFailover", roleProperties.optString("websphere.applicationconfig.enablesfsbfailover", None));
  Util.addIfNotNone(properties, "overrideDefaultDRSSettings", roleProperties.optString("websphere.applicationconfig.overridedefaultdrssettings", None));
  print "Creating ApplicationConfig with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ApplicationConfig", parentid, properties);
  
  sessionManager = Util.getRequiredAttribute(objid, 'sessinManagement',"ApplicationConfig");
  if sessionManager is not None and len(sessionManager) > 0:
    Util.remove(sessionManager);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDRSSettings":
        DRSSettings.create(objid, curjsonobject);
      elif currole == "WebSphereSessionManager":
        SessionManager.create(objid, curjsonobject, None);
  Util.popPathElement('ApplicationConfig');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationconfig.enablesfsbfailover", None), "enableSFSBFailover","ApplicationConfig");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.applicationconfig.overridedefaultdrssettings", None), "overrideDefaultDRSSettings","ApplicationConfig");
  if len(atts) != 0:
    print "Modifying ApplicationConfig with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "ApplicationConfig configuration up to date.";
    
  drsSettings = Util.getOptionalAttribute(objid, 'drsSettings',"ApplicationConfig");
  if drsSettings is not None and len(drsSettings) > 0:
    Util.remove(drsSettings);
    
  sessionManager = Util.getRequiredAttribute(objid, 'sessionManagement',"ApplicationConfig");
  if sessionManager is not None and len(sessionManager) > 0:
    Util.remove(sessionManager);
    
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDRSSettings":
        DRSSettings.create(objid, curjsonobject);
      elif currole == "WebSphereSessionManager":
        SessionManager.create(objid, curjsonobject, None);


  Util.popPathElement('ApplicationConfig');
