from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SIBContextInfo import SIBContextInfo;
from SIBQualifiedDestinationName import SIBQualifiedDestinationName;
from SIBDestinationMediationRef import SIBDestinationMediationRef;
from SIBLocalizationPointRef import SIBLocalizationPointRef;

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.receiveallowed", objid, "receiveAllowed","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.persistredeliverycount", objid, "persistRedeliveryCount","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.defaultpriority", objid, "defaultPriority","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.identifier", objid, "identifier","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.instancetype", objid, "instanceType","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.maxreliability", objid, "maxReliability","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.receiveexclusive", objid, "receiveExclusive","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.exceptiondestination", objid, "exceptionDestination","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.overrideofqosbyproducerallowed", objid, "overrideOfQOSByProducerAllowed","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.blockedretrytimeout", objid, "blockedRetryTimeout","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.reliability", objid, "reliability","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.description", objid, "description","SIBQueue");
#  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.uuid", objid, "uuid","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.exceptiondiscardreliability", objid, "exceptionDiscardReliability","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.maintainstrictmessageorder", objid, "maintainStrictMessageOrder","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.sendallowed", objid, "sendAllowed","SIBQueue");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibqueue.maxfaileddeliveries", objid, "maxFailedDeliveries","SIBQueue");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  contextInfos = Util.parseConfigIdListAttribute(objid, 'contextInfo', 'SIBQueue');
  for contextInfo in contextInfos:
    if len(contextInfo) > 0:
      returndict = Util.createTypeFolder(respath, "SIBContextInfo", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBContextInfo._export(contextInfo, currespath, "SIBContextInfo%s" % i));
      i = i + 1;

  i = 0;
  defaultForwardRoutingPaths = Util.parseConfigIdListAttribute(objid, 'defaultForwardRoutingPath', 'SIBQueue');
  for defaultForwardRoutingPath in defaultForwardRoutingPaths:
    if len(defaultForwardRoutingPath) > 0:
      returndict = Util.createTypeFolder(respath, "SIBQualifiedDestinationName", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBQualifiedDestinationName._export(defaultForwardRoutingPath, currespath, "SIBQualifiedDestinationName%s" % i));
      i = i + 1;

  i = 0;
  destinationMediationRefs = Util.parseConfigIdListAttribute(objid, 'destinationMediationRef', 'SIBQueue');
  for destinationMediationRef in destinationMediationRefs:
    if len(destinationMediationRef) > 0:
      returndict = Util.createTypeFolder(respath, "SIBDestinationMediationRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBDestinationMediationRef._export(destinationMediationRef, currespath, "SIBDestinationMediationRef%s" % i));
      i = i + 1;

  i = 0;
  localizationPointRefs = Util.parseConfigIdListAttribute(objid, 'localizationPointRefs', 'SIBQueue');
  for localizationPointRef in localizationPointRefs:
    if len(localizationPointRef) > 0:
      returndict = Util.createTypeFolder(respath, "SIBLocalizationPointRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBLocalizationPointRef._export(localizationPointRef, currespath, "SIBDestinationMediationRef%s" % i));
      i = i + 1;

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "receiveAllowed", roleProperties.optString("websphere.sibqueue.receiveallowed", None));
  Util.addIfNotNone(properties, "persistRedeliveryCount", roleProperties.optString("websphere.sibqueue.persistredeliverycount", "false"));
  Util.addIfNotNone(properties, "defaultPriority", roleProperties.optString("websphere.sibqueue.defaultpriority", None));
  Util.addIfNotNone(properties, "identifier", roleProperties.optString("websphere.sibqueue.identifier", None));
  Util.addIfNotNone(properties, "instanceType", roleProperties.optString("websphere.sibqueue.instancetype", None));
  Util.addIfNotNone(properties, "maxReliability", roleProperties.optString("websphere.sibqueue.maxreliability", None));
  Util.addIfNotNone(properties, "receiveExclusive", roleProperties.optString("websphere.sibqueue.receiveexclusive", None));
  Util.addIfNotNone(properties, "exceptionDestination", roleProperties.optString("websphere.sibqueue.exceptiondestination", None));
  Util.addIfNotNone(properties, "overrideOfQOSByProducerAllowed", roleProperties.optString("websphere.sibqueue.overrideofqosbyproducerallowed", None));
  Util.addIfNotNone(properties, "blockedRetryTimeout", roleProperties.optString("websphere.sibqueue.blockedretrytimeout", None));
  Util.addIfNotNone(properties, "reliability", roleProperties.optString("websphere.sibqueue.reliability", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.sibqueue.description", None));
  Util.addIfNotNone(properties, "uuid", roleProperties.optString("websphere.sibqueue.uuid", None));
  Util.addIfNotNone(properties, "exceptionDiscardReliability", roleProperties.optString("websphere.sibqueue.exceptiondiscardreliability", "BEST_EFFORT_NONPERSISTENT"));
  Util.addIfNotNone(properties, "maintainStrictMessageOrder", roleProperties.optString("websphere.sibqueue.maintainstrictmessageorder", None));
  Util.addIfNotNone(properties, "sendAllowed", roleProperties.optString("websphere.sibqueue.sendallowed", None));
  Util.addIfNotNone(properties, "maxFailedDeliveries", roleProperties.optString("websphere.sibqueue.maxfaileddeliveries", None));
  print "Creating SIBQueue with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SIBQueue", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereSIBContextInfo":
        SIBContextInfo.create(objid, curjsonobject);
      elif currole == "WebSphereSIBQualifiedDestinationName":
        SIBContextInfo.create(objid, curjsonobject);
      elif currole == "WebSphereSIBDestinationMediationRef":
        SIBDestinationMediationRef.create(objid, curjsonobject);
      elif currole == "WebSphereSIBLocalizationPointRef":
        SIBLocalizationPointRef.create(objid, curjsonobject);

  Util.popPathElement('SIBQueue');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.receiveallowed", None), "receiveAllowed","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.persistredeliverycount", "false"), "persistRedeliveryCount","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.defaultpriority", None), "defaultPriority","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.identifier", None), "identifier","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.instancetype", None), "instanceType","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.maxreliability", None), "maxReliability","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.receiveexclusive", None), "receiveExclusive","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.exceptiondestination", None), "exceptionDestination","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.overrideofqosbyproducerallowed", None), "overrideOfQOSByProducerAllowed","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.blockedretrytimeout", None), "blockedRetryTimeout","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.reliability", None), "reliability","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.description", None), "description","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.uuid", None), "uuid","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.exceptiondiscardreliability", "BEST_EFFORT_NONPERSISTENT"), "exceptionDiscardReliability","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.maintainstrictmessageorder", None), "maintainStrictMessageOrder","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.sendallowed", None), "sendAllowed","SIBQueue");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibqueue.maxfaileddeliveries", None), "maxFailedDeliveries","SIBQueue");
  if len(atts) != 0:
    print "Modifying SIBQueue with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  contextInfos = Util.parseConfigIdListAttribute(objid, 'contextInfo', 'SIBQueue');
  for contextInfo in contextInfos:
    if len(contextInfo) > 0:
      Util.remove(contextInfo);

  defaultForwardRoutingPaths = Util.parseConfigIdListAttribute(objid, 'defaultForwardRoutingPath', 'SIBQueue');
  for defaultForwardRoutingPath in defaultForwardRoutingPaths:
    if len(defaultForwardRoutingPath) > 0:
      Util.remove(defaultForwardRoutingPath);

  destinationMediationRefs = Util.parseConfigIdListAttribute(objid, 'destinationMediationRef', 'SIBQueue');
  for destinationMediationRef in destinationMediationRefs:
    if len(destinationMediationRef) > 0:
      Util.remove(destinationMediationRef);

  localizationPointRefs = Util.parseConfigIdListAttribute(objid, 'localizationPointRefs', 'SIBQueue');
  for localizationPointRef in localizationPointRefs:
    if len(localizationPointRef) > 0:
      Util.remove(localizationPointRef);

  replyDestination = Util.getOptionalAttribute(objid, 'replyDestination', 'SIBQueue');
  if replyDestination is not None and len(replyDestination) > 0:
    Util.remove(replyDestination);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereSIBContextInfo":
        SIBContextInfo.create(objid, curjsonobject);
      elif currole == "WebSphereSIBQualifiedDestinationName":
        SIBQualifiedDestinationName.create(objid, curjsonobject);
      elif currole == "WebSphereSIBDestinationMediationRef":
        SIBDestinationMediationRef.create(objid, curjsonobject);
      elif currole == "WebSphereSIBLocalizationPointRef":
        SIBLocalizationPointRef.create(objid, curjsonobject);

  Util.popPathElement('SIBQueue');
