from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from ApplicationServerMapping import ApplicationServerMapping
from GenericServerClusterMapping import GenericServerClusterMapping
from ApplicationServerClusterMapping import ApplicationServerClusterMapping
from StandAloneApplicationServerMapping import StandAloneApplicationServerMapping

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.blaid", objid, "blaID","CustomAdvisor");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.enablelogging", objid, "enableLogging","CustomAdvisor");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.pollinterval", objid, "pollInterval","CustomAdvisor");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.cuid", objid, "cuID","CustomAdvisor");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.iotimeout", objid, "ioTimeout","CustomAdvisor");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.connecttimeout", objid, "connectTimeout","CustomAdvisor");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.enablelogfilewrapping", objid, "enableLogFileWrapping","CustomAdvisor");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customadvisor.logfilesize", objid, "logFileSize","CustomAdvisor");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"CustomAdvisor");

  counterApplicationServerMapping = 0;
  counterGenericServerClusterMapping = 0;
  counterApplicationServerClusterMapping = 0;
  counterStandAloneApplicationServerMapping = 0;

  customAdvisorMappings = Util.parseConfigIdListAttribute(objid, 'customAdvisorMappings',"CustomAdvisor");
  for customAdvisorMapping in customAdvisorMappings:
    if customAdvisorMapping is not None and len(customAdvisorMapping) > 0:
      if customAdvisorMapping.find("#ApplicationServerMapping_") != -1:
        returndict = Util.createTypeFolder(respath, "ApplicationServerMapping", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, ApplicationServerMapping._export(customAdvisorMapping, currespath, 'Application Server Mapping%s' % counterApplicationServerMapping));
        counterApplicationServerMapping = counterApplicationServerMapping + 1;
      elif customAdvisorMapping.find("#GenericServerClusterMapping_") != -1:
        returndict = Util.createTypeFolder(respath, "GenericServerClusterMapping", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, GenericServerClusterMapping._export(customAdvisorMapping, currespath, 'Generic Server Cluster Mapping%s' % counterGenericServerClusterMapping));
        counterGenericServerClusterMapping = counterGenericServerClusterMapping + 1;
      elif customAdvisorMapping.find("#ApplicationServerClusterMapping_") != -1:
        returndict = Util.createTypeFolder(respath, "ApplicationServerClusterMapping", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, ApplicationServerClusterMapping._export(customAdvisorMapping, currespath, 'Application Server Cluster Mapping%s' % counterApplicationServerClusterMapping));
        counterApplicationServerClusterMapping = counterApplicationServerClusterMapping + 1;
      elif customAdvisorMapping.find("#StandAloneApplicationServerMapping_") != -1:
        returndict = Util.createTypeFolder(respath, "StandAloneApplicationServerMapping", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, StandAloneApplicationServerMapping._export(customAdvisorMapping, currespath, 'Stand Alone Application Server Mapping%s' % counterStandAloneApplicationServerMapping));
        counterStandAloneApplicationServerMapping = counterStandAloneApplicationServerMapping + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "blaID", roleProperties.optString("websphere.customadvisor.blaid", None));
  Util.addIfNotNone(properties, "enableLogging", roleProperties.optString("websphere.customadvisor.enablelogging", None));
  Util.addIfNotNone(properties, "pollInterval", roleProperties.optString("websphere.customadvisor.pollinterval", None));
  Util.addIfNotNone(properties, "cuID", roleProperties.optString("websphere.customadvisor.cuid", None));
  Util.addIfNotNone(properties, "ioTimeout", roleProperties.optString("websphere.customadvisor.iotimeout", None));
  Util.addIfNotNone(properties, "connectTimeout", roleProperties.optString("websphere.customadvisor.connecttimeout", None));
  Util.addIfNotNone(properties, "enableLogFileWrapping", roleProperties.optString("websphere.customadvisor.enablelogfilewrapping", None));
  Util.addIfNotNone(properties, "logFileSize", roleProperties.optString("websphere.customadvisor.logfilesize", None));
  print "Creating CustomAdvisor with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("CustomAdvisor", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereApplicationServerMapping":
        ApplicationServerMapping.create(objid, curjsonobject);
      elif currole == "WebSphereGenericServerClusterMapping":
        GenericServerClusterMapping.create(objid, curjsonobject);
      elif currole == "WebSphereApplicationServerClusterMapping":
        ApplicationServerClusterMapping.create(objid, curjsonobject);
      elif currole == "WebSphereApplicationServerClusterMapping":
        ApplicationServerClusterMapping.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CustomAdvisor');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.blaid", None), "blaID","CustomAdvisor");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.enablelogging", None), "enableLogging","CustomAdvisor");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.pollinterval", None), "pollInterval","CustomAdvisor");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.cuid", None), "cuID","CustomAdvisor");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.iotimeout", None), "ioTimeout","CustomAdvisor");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.connecttimeout", None), "connectTimeout","CustomAdvisor");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.enablelogfilewrapping", None), "enableLogFileWrapping","CustomAdvisor");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customadvisor.logfilesize", None), "logFileSize","CustomAdvisor");
  if len(atts) != 0:
    print "Modifying CustomAdvisor with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  customAdvisorMappings = Util.parseConfigIdListAttribute(objid, 'customAdvisorMappings',"CustomAdvisor");
  for customAdvisorMapping in customAdvisorMappings:
    if len(customAdvisorMapping) > 0:
      Util.remove(customAdvisorMapping);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereApplicationServerMapping":
        ApplicationServerMapping.create(objid, curjsonobject);
      elif currole == "WebSphereGenericServerClusterMapping":
        GenericServerClusterMapping.create(objid, curjsonobject);
      elif currole == "WebSphereApplicationServerClusterMapping":
        ApplicationServerClusterMapping.create(objid, curjsonobject);
      elif currole == "WebSphereApplicationServerClusterMapping":
        ApplicationServerClusterMapping.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CustomAdvisor');
