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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.eventgroupprofile.topicjndiname", objid, "topicJNDIName","EventGroupProfile");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.eventgroupprofile.eventgroupname", objid, "eventGroupName","EventGroupProfile");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.eventgroupprofile.topicconnectionfactoryjndiname", objid, "topicConnectionFactoryJNDIName","EventGroupProfile");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.eventgroupprofile.eventselectorstring", objid, "eventSelectorString","EventGroupProfile");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.eventgroupprofile.persistevents", objid, "persistEvents","EventGroupProfile");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  distributionqueues = Util.parseConfigIdListAttribute(objid, 'distributionQueues',"EventGroupProfile");
  for distributionqueue in distributionqueues:
    if len(distributionqueue) > 0:
      returndict = Util.createTypeFolder(respath, "DistributionQueue", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, DistributionQueue._export(distributionqueue, currespath, "DistributionQueue%s" % i));
      i = i + 1;
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('EventGroupProfile');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "topicJNDIName", roleProperties.optString("websphere.eventgroupprofile.topicjndiname", None));
  Util.addIfNotNone(properties, "eventGroupName", roleProperties.optString("websphere.eventgroupprofile.eventgroupname", None));
  Util.addIfNotNone(properties, "topicConnectionFactoryJNDIName", roleProperties.optString("websphere.eventgroupprofile.topicconnectionfactoryjndiname", None));
  Util.addIfNotNone(properties, "eventSelectorString", roleProperties.optString("websphere.eventgroupprofile.eventselectorstring", None));
  Util.addIfNotNone(properties, "persistEvents", roleProperties.optString("websphere.eventgroupprofile.persistevents", None));
  print "Creating EventGroupProfile with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("EventGroupProfile", parentid, properties);

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.eventgroupprofile.topicjndiname", None), "topicJNDIName","EventGroupProfile");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.eventgroupprofile.eventgroupname", None), "eventGroupName","EventGroupProfile");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.eventgroupprofile.topicconnectionfactoryjndiname", None), "topicConnectionFactoryJNDIName","EventGroupProfile");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.eventgroupprofile.eventselectorstring", None), "eventSelectorString","EventGroupProfile");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.eventgroupprofile.persistevents", None), "persistEvents","EventGroupProfile");
  if len(atts) != 0:
    print "Modifying EventGroupProfile with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  distributionqueues = Util.parseConfigIdListAttribute(objid, 'distributionQueues',"EventGroupProfile");
  for distributionqueue in distributionqueues:
    if len(distributionqueue) > 0:
      Util.remove(distributionqueue);

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

  Util.popPathElement('EventGroupProfile');
