from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from ProcessExecution import ProcessExecution
from OutputRedirect import OutputRedirect 
from MonitoringPolicy import MonitoringPolicy
from Property import Property
from utilities import Util

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.processdef.executablename", objid, "executableName","ProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.processdef.stopcommand", objid, "stopCommand","ProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.processdef.stopcommandargs", objid, "stopCommandArgs","ProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.processdef.terminatecommand", objid, "terminateCommand","ProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.processdef.workingdirectory", objid, "workingDirectory","ProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.processdef.startcommandargs", objid, "startCommandArgs","ProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.processdef.executablearguments", objid, "executableArguments","ProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.processdef.startcommand", objid, "startCommand","ProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.processdef.terminatecommandargs", objid, "terminateCommandArgs","ProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.processdef.processtype", objid, "processType","ProcessDef");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];

  typeFolders = {};
  procexe = Util.getOptionalAttribute(objid, 'execution', 'ProcessDef');
  if procexe is not None and len(procexe) > 0:
    returndict = Util.createTypeFolder(respath, 'ProcessExecution', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ProcessExecution._export(procexe, currespath, "ProcessExecution"));
  ioRedirect = Util.getOptionalAttribute(objid, 'ioRedirect', 'ProcessDef');
  if ioRedirect is not None and len(ioRedirect) > 0:
    returndict = Util.createTypeFolder(respath, 'OutputRedirect', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, OutputRedirect._export(ioRedirect, currespath, "OutputRedirect"));
  policy = Util.getOptionalAttribute(objid, 'monitoringPolicy', 'ProcessDef');
  if policy is not None and len(policy) > 0:
    returndict = Util.createTypeFolder(respath, 'MonitoringPolicy', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, MonitoringPolicy._export(policy, currespath, "MonitoringPolicy"));

  extraObjects = Property.exportProperties(objid,respath,extraObjects,typeFolders,'environment',"ProcessDef" );

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "executableName", roleProperties.optString("websphere.processdef.executablename", None));
  Util.addIfNotNone(properties, "stopCommand", roleProperties.optString("websphere.processdef.stopcommand", None));
  Util.addPathProperty(properties, "stopCommandArgs", roleProperties.optString("websphere.processdef.stopcommandargs", None));
  Util.addIfNotNone(properties, "terminateCommand", roleProperties.optString("websphere.processdef.terminatecommand", None));
  Util.addIfNotNone(properties, "workingDirectory", roleProperties.optString("websphere.processdef.workingdirectory", None));
  Util.addPathProperty(properties, "startCommandArgs", roleProperties.optString("websphere.processdef.startcommandargs", None));
  Util.addPathProperty(properties, "executableArguments", roleProperties.optString("websphere.processdef.executablearguments", None));
  Util.addIfNotNone(properties, "startCommand", roleProperties.optString("websphere.processdef.startcommand", None));
  Util.addPathProperty(properties, "terminateCommandArgs", roleProperties.optString("websphere.processdef.terminatecommandargs", None));
  Util.addIfNotNone(properties, "processType", roleProperties.optString("websphere.processdef.processtype", None));
  print "Creating ProcessDef with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ProcessDef", parentid, properties, attName);

  Property.removeProperties(objid, 'environment',"ProcessDef");

  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 == "WebSphereProcessExecution":
          ProcessExecution.create(objid, curjsonobject);
        elif currole == "WebSphereOutputRedirect":
          OutputRedirect.create(objid, curjsonobject);
        elif currole == "WebSphereMonitoringPolicy":
          MonitoringPolicy.create(objid, curjsonobject);
  Util.popPathElement('ProcessDef');


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.executablename", None), "executableName","ProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.stopcommand", None), "stopCommand","ProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.stopcommandargs", None), "stopCommandArgs","ProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.terminatecommand", None), "terminateCommand","ProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.workingdirectory", None), "workingDirectory","ProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.startcommandargs", None), "startCommandArgs","ProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.executablearguments", None), "executableArguments","ProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.startcommand", None), "startCommand","ProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.terminatecommandargs", None), "terminateCommandArgs","ProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.processdef.processtype", None), "processType","ProcessDef");
  if len(atts) != 0:
    print "Modifying ProcessDef with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'environment',"ProcessDef");

  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 == "WebSphereProcessExecution":
          ProcessExecution.update(objid, curjsonobject);
        elif currole == "WebSphereOutputRedirect":
          OutputRedirect.update(objid, curjsonobject);
        elif currole == "WebSphereMonitoringPolicy":
          MonitoringPolicy.update(objid, curjsonobject);


  Util.popPathElement('ProcessDef');
