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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.stack.inviteautoreply100", objid, "inviteAutoReply100","Stack");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.stack.outboundproxy", objid, "outboundProxy","Stack");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.stack.mtu", objid, "MTU","Stack");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.stack.outboundconnectiontimeout", objid, "outboundConnectionTimeout","Stack");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.stack.hidemessagebody", objid, "hideMessageBody","Stack");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  timers = Util.getRequiredAttribute(objid, 'timers',"Stack");
  if timers is not None and len(timers) > 0:
    returndict = Util.createTypeFolder(respath, "Timers", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, Timers._export(timers, currespath, "Timers"));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "inviteAutoReply100", roleProperties.optString("websphere.stack.inviteautoreply100", None));
  Util.addIfNotNone(properties, "outboundProxy", roleProperties.optString("websphere.stack.outboundproxy", None));
  Util.addIfNotNone(properties, "MTU", roleProperties.optString("websphere.stack.mtu", None));
  Util.addIfNotNone(properties, "outboundConnectionTimeout", roleProperties.optString("websphere.stack.outboundconnectiontimeout", None));
  Util.addIfNotNone(properties, "hideMessageBody", roleProperties.optString("websphere.stack.hidemessagebody", None));
  print "Creating Stack with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("Stack", parentid, properties);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children:
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereTimers":
        Timers.create(objid, curjsonobject);
  Util.popPathElement('Stack');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.stack.inviteautoreply100", None), "inviteAutoReply100","Stack");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.stack.outboundproxy", None), "outboundProxy","Stack");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.stack.mtu", None), "MTU","Stack");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.stack.outboundconnectiontimeout", None), "outboundConnectionTimeout","Stack");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.stack.hidemessagebody", None), "hideMessageBody","Stack");
  if len(atts) != 0:
    print "Modifying Stack with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  timers = Util.getRequiredAttribute(objid, 'timers',"Stack");
  if timers is not None and len(timers) > 0:
    Util.remove(timers);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children:
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereTimers":
        Timers.create(objid, curjsonobject);

  Util.popPathElement('Stack');
