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","JavaProcessDef");

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


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

  roleProperties = JSONObject();

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

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

  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('JavaProcessDef');
  return result;

def doImportPartial(containmentpath, roleName, jsonobject):
  doImport(containmentpath, roleName, jsonobject);

def doImport(containmentpath, roleName, jsonobject):
  objids = Util.getid(containmentpath).splitlines();
  if len(objids) > 1:
    raise Exception("Unable to uniquely identify JavaProcessDef to import.");

  objid = Util.getid(containmentpath);
  
  if objid == None or objid == "":
    if Util.__removePartialConfig__ == "false":
      index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
      parentconpath = containmentpath[0:index];
      parentid = Util.getid(parentconpath);
      if parentid == None or len(parentid) == 0:
        raise Exception("Parent does not exist to create JavaProcessDef on.");
      objid = create(parentid, jsonobject);
  else:
    if Util.__removePartialConfig__ == "true":
      #Util.removePartialApply(objid);
      #objid = None;
      raise Exception("Partial remove not supported for JavaProcessDef object!");
    else:
      update(objid, jsonobject);
  return objid

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  props = Util.parseConfigIdListAttribute(objid, 'environment',"JavaProcessDef");
  for prop in props:
    Util.remove(prop);

  #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":
          proc = Util.getOptionalAttribute(objid, 'execution', 'JavaProcessDef');
          if proc is not None and len(proc) > 0:
            ProcessExecution.update(proc, curjsonobject);
          else:
            ProcessExecution.create(objid, curjsonobject);
        elif currole == "WebSphereOutputRedirect":
          output = Util.getOptionalAttribute(objid, 'ioRedirect', 'JavaProcessDef');
          if output is not None and len(output) > 0:
            OutputRedirect.update(output, curjsonobject);
          else:
            OutputRedirect.create(objid, curjsonobject);
        elif currole == "WebSphereMonitoringPolicy":
          monitor = Util.getOptionalAttribute(objid, 'monitoringPolicy', 'JavaProcessDef');
          if monitor is not None and len(monitor) > 0:
            MonitoringPolicy.update(monitor, curjsonobject);
          else:
            MonitoringPolicy.create(objid, curjsonobject);
  Util.popPathElement('JavaProcessDef');
