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 JavaVirtualMachine import JavaVirtualMachine
from utilities import Util

__name_att__ = None;

def getJVMEntriesObjIds(objid):
  return Util.parseConfigIdListAttribute(objid, "jvmEntries","NamedJavaProcessDef");

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


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

  roleProperties = JSONObject();

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

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

  i = 0;  
  jvms = getJVMEntriesObjIds(objid);
  for jvm in jvms:
    if jvm is not None and len(jvm) > 0:
      returndict = Util.createTypeFolder(respath, "JavaVirtualMachine", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, JavaVirtualMachine._export(jvm, currespath, "JavaVirtualMachine%s" % i));
      i=i+1; 

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  #remove children then readd
  for jvm in getJVMEntriesObjIds(objid):
    Util.remove(jvm);

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  #remove children then readd
  for jvm in getJVMEntriesObjIds(objid):
    Util.remove(jvm);

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

  Util.popPathElement('NamedJavaProcessDef');
