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('SIBPort')


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

  roleProperties = JSONObject();

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

  i = 0;
  contextInfos = Util.parseConfigIdListAttribute(objid, 'contextInfo', 'SIBPort');
  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', 'SIBPort');
  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', 'SIBPort');
  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', 'SIBPort');
  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.getRequiredAttribute(objid, 'replyDestination', 'SIBPort');
  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('SIBPort');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

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

  replyDestination = Util.getOptionalAttribute(objid, 'replyDestination', 'SIBPort');
  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('SIBPort');
