from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Property import Property
from HPELLog import HPELLog
from HPELTrace import HPELTrace
from HPELTextLog import HPELTextLog
from utilities import Util

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.highperformanceextensiblelogging.startuptracespec", objid, "startupTraceSpec","HighPerformanceExtensibleLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.highperformanceextensiblelogging.correlationidenabled", objid, "correlationIdEnabled","HighPerformanceExtensibleLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.highperformanceextensiblelogging.enable", objid, "enable","HighPerformanceExtensibleLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.highperformanceextensiblelogging.stacktracesuppressionenabled", objid, "stackTraceSuppressionEnabled","HighPerformanceExtensibleLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.highperformanceextensiblelogging.rawtracefilterenabled", objid, "rawTraceFilterEnabled","HighPerformanceExtensibleLogging");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

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

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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "startupTraceSpec", roleProperties.optString("websphere.highperformanceextensiblelogging.startuptracespec", None));
  Util.addIfNotNone(properties, "correlationIdEnabled", roleProperties.optString("websphere.highperformanceextensiblelogging.correlationidenabled", None));
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.highperformanceextensiblelogging.enable", None));
  Util.addIfNotNone(properties, "stackTraceSuppressionEnabled", roleProperties.optString("websphere.highperformanceextensiblelogging.stacktracesuppressionenabled", None));
  Util.addIfNotNone(properties, "rawTraceFilterEnabled", roleProperties.optString("websphere.highperformanceextensiblelogging.rawtracefilterenabled", None));
  print "Creating HighPerformanceExtensibleLogging with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("HighPerformanceExtensibleLogging", 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 == "WebSphereHPELLog":
          HPELLog.create(objid, curjsonobject);
        elif currole == "WebSphereHPELTrace":
          HPELTrace.create(objid, curjsonobject);
        elif currole == "WebSphereHPELTextLog":
          HPELTextLog.create(objid, curjsonobject);
  Util.popPathElement('HighPerformanceExtensibleLogging');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.highperformanceextensiblelogging.startuptracespec", None), "startupTraceSpec","HighPerformanceExtensibleLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.highperformanceextensiblelogging.correlationidenabled", None), "correlationIdEnabled","HighPerformanceExtensibleLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.highperformanceextensiblelogging.enable", None), "enable","HighPerformanceExtensibleLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.highperformanceextensiblelogging.stacktracesuppressionenabled", None), "stackTraceSuppressionEnabled","HighPerformanceExtensibleLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.highperformanceextensiblelogging.rawtracefilterenabled", None), "rawTraceFilterEnabled","HighPerformanceExtensibleLogging");
  if len(atts) != 0:
    print "Modifying HighPerformanceExtensibleLogging with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

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

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

  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 == "WebSphereHPELLog":
          HPELLog.create(objid, curjsonobject);
        elif currole == "WebSphereSessionHPELTrace":
          HPELTrace.create(objid, curjsonobject);
        elif currole == "WebSphereHPELTextLog":
          HPELTextLog.create(objid, curjsonobject);

  Util.popPathElement('HighPerformanceExtensibleLogging');
