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('NamedProcessDef')


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.startcommand", objid, "startCommand","NamedProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.namedprocessdef.stopcommandargs", objid, "stopCommandArgs","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.usernamevar", objid, "usernameVar","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.usernameval", objid, "usernameVal","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.terminatecommand", objid, "terminateCommand","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.processtype", objid, "processType","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.executablename", objid, "executableName","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.osnames", objid, "osnames","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.workingdirectory", objid, "workingDirectory","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.stopcommand", objid, "stopCommand","NamedProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.namedprocessdef.startcommandargs", objid, "startCommandArgs","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.pidvarname", objid, "pidVarName","NamedProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.namedprocessdef.executablearguments", objid, "executableArguments","NamedProcessDef");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.namedprocessdef.terminatecommandargs", objid, "terminateCommandArgs","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.passwordvar", objid, "passwordVar","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.passwordval", objid, "passwordVal","NamedProcessDef");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedprocessdef.name", objid, "name","NamedProcessDef");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];

  typeFolders = {};
  procexe = Util.getOptionalAttribute(objid, 'execution', 'NamedProcessDef');
  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', 'NamedProcessDef');
  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', 'NamedProcessDef');
  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',"NamedProcessDef");

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "startCommand", roleProperties.optString("websphere.namedprocessdef.startcommand", None));
  Util.addPathProperty(properties, "stopCommandArgs", roleProperties.optString("websphere.namedprocessdef.stopcommandargs", None));
  Util.addIfNotNone(properties, "usernameVar", roleProperties.optString("websphere.namedprocessdef.usernamevar", None));
  Util.addIfNotNone(properties, "usernameVal", roleProperties.optString("websphere.namedprocessdef.usernameval", None));
  Util.addIfNotNone(properties, "terminateCommand", roleProperties.optString("websphere.namedprocessdef.terminatecommand", None));
  Util.addIfNotNone(properties, "processType", roleProperties.optString("websphere.namedprocessdef.processtype", None));
  Util.addIfNotNone(properties, "executableName", roleProperties.optString("websphere.namedprocessdef.executablename", None));
  Util.addIfNotNone(properties, "osnames", roleProperties.optString("websphere.namedprocessdef.osnames", None));
  Util.addIfNotNone(properties, "workingDirectory", roleProperties.optString("websphere.namedprocessdef.workingdirectory", None));
  Util.addIfNotNone(properties, "stopCommand", roleProperties.optString("websphere.namedprocessdef.stopcommand", None));
  Util.addPathProperty(properties, "startCommandArgs", roleProperties.optString("websphere.namedprocessdef.startcommandargs", None));
  Util.addIfNotNone(properties, "pidVarName", roleProperties.optString("websphere.namedprocessdef.pidvarname", None));
  Util.addPathProperty(properties, "executableArguments", roleProperties.optString("websphere.namedprocessdef.executablearguments", None));
  Util.addPathProperty(properties, "terminateCommandArgs", roleProperties.optString("websphere.namedprocessdef.terminatecommandargs", None));
  Util.addIfNotNone(properties, "passwordVar", roleProperties.optString("websphere.namedprocessdef.passwordvar", None));
  Util.addIfNotNone(properties, "passwordVal", roleProperties.optString("websphere.namedprocessdef.passwordval", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.namedprocessdef.name", None));
  print "Creating NamedProcessDef with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("NamedProcessDef", parentid, properties, attName);

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

  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('NamedProcessDef');


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.startcommand", None), "startCommand","NamedProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.stopcommandargs", None), "stopCommandArgs","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.usernamevar", None), "usernameVar","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.usernameval", None), "usernameVal","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.terminatecommand", None), "terminateCommand","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.processtype", None), "processType","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.executablename", None), "executableName","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.osnames", None), "osnames","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.workingdirectory", None), "workingDirectory","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.stopcommand", None), "stopCommand","NamedProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.startcommandargs", None), "startCommandArgs","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.pidvarname", None), "pidVarName","NamedProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.executablearguments", None), "executableArguments","NamedProcessDef");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.terminatecommandargs", None), "terminateCommandArgs","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.passwordvar", None), "passwordVar","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.passwordval", None), "passwordVal","NamedProcessDef");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namedprocessdef.name", None), "name","NamedProcessDef");
  if len(atts) != 0:
    print "Modifying NamedProcessDef with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  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('NamedProcessDef');
