from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from TraceLog import TraceLog
from utilities import Util
from Property import Property

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.traceservice.startuptracespecification", objid, "startupTraceSpecification","TraceService");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.traceservice.enable", objid, "enable","TraceService");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.traceservice.memorybuffersize", objid, "memoryBufferSize","TraceService");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.traceservice.traceformat", objid, "traceFormat","TraceService");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.traceservice.traceoutputtype", objid, "traceOutputType","TraceService");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"TraceService");
  traceLog = Util.getOptionalAttribute(objid, 'traceLog', 'TraceService');
  if traceLog is not None and len(traceLog) > 0:
    returndict = Util.createTypeFolder(respath, "TraceLog", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, TraceLog._export(traceLog, currespath, 'TraceLog'));
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('TraceService');
  return result;


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "startupTraceSpecification", roleProperties.optString("websphere.traceservice.startuptracespecification", None));
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.traceservice.enable", None));
  Util.addIfNotNone(properties, "memoryBufferSize", roleProperties.optString("websphere.traceservice.memorybuffersize", None));
  Util.addIfNotNone(properties, "traceFormat", roleProperties.optString("websphere.traceservice.traceformat", None));
  Util.addIfNotNone(properties, "traceOutputType", roleProperties.optString("websphere.traceservice.traceoutputtype", None));
  print "Creating TraceService with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("TraceService", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereTraceLog":
        TraceLog.create(objid, curjsonobject);
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('TraceService');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.traceservice.startuptracespecification", None), "startupTraceSpecification","TraceService");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.traceservice.enable", None), "enable","TraceService");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.traceservice.memorybuffersize", None), "memoryBufferSize","TraceService");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.traceservice.traceformat", None), "traceFormat","TraceService");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.traceservice.traceoutputtype", None), "traceOutputType","TraceService");
  if len(atts) != 0:
    print "Modifying TraceService with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  traceLog = Util.getOptionalAttribute(objid, 'traceLog', 'TraceService');
  if traceLog is not None and len(traceLog) > 0:
    Util.remove(traceLog);
  Property.removeProperties(objid, 'properties',"TraceService");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereTraceLog":
        TraceLog.create(objid, curjsonobject);
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('TraceService');
