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


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

  roleProperties = JSONObject();

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

  replyDestination = Util.getOptionalAttribute(objid, 'replyDestination', 'SIBDestination');
  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('SIBDestination');
    
def getSIBDestinations(objid):
  sibDestinations = Util.getAssociatedObjects(objid, "SIBDestination");
  return sibDestinations;     

