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


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

  roleProperties = JSONObject();

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  Util.popPathElement('SIBWebService');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

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

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