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


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

  roleProperties = JSONObject();

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

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