from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SIBPSBBrokerProfile import SIBPSBBrokerProfile
from SIBMQLinkReceiverChannel import SIBMQLinkReceiverChannel
from SIBMQLinkSenderChannel import SIBMQLinkSenderChannel


__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.uuid", objid, "uuid","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.sequencewrap", objid, "sequenceWrap","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.name", objid, "name","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.initialstate", objid, "initialState","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.targetuuid", objid, "targetUuid","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.nonpersistentmessagespeed", objid, "nonPersistentMessageSpeed","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.adoptable", objid, "adoptable","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.heartbeat", objid, "heartBeat","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.batchsize", objid, "batchSize","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.qmname", objid, "qmName","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.maxmsgsize", objid, "maxMsgSize","SIBMQLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibmqlink.description", objid, "description","SIBMQLink");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "uuid", roleProperties.optString("websphere.sibmqlink.uuid", None));
  Util.addIfNotNone(properties, "sequenceWrap", roleProperties.optString("websphere.sibmqlink.sequencewrap", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.sibmqlink.name", None));
  Util.addIfNotNone(properties, "initialState", roleProperties.optString("websphere.sibmqlink.initialstate", None));
  Util.addIfNotNone(properties, "targetUuid", roleProperties.optString("websphere.sibmqlink.targetuuid", None));
  Util.addIfNotNone(properties, "nonPersistentMessageSpeed", roleProperties.optString("websphere.sibmqlink.nonpersistentmessagespeed", None));
  Util.addIfNotNone(properties, "adoptable", roleProperties.optString("websphere.sibmqlink.adoptable", None));
  Util.addIfNotNone(properties, "heartBeat", roleProperties.optString("websphere.sibmqlink.heartbeat", None));
  Util.addIfNotNone(properties, "batchSize", roleProperties.optString("websphere.sibmqlink.batchsize", None));
  Util.addIfNotNone(properties, "qmName", roleProperties.optString("websphere.sibmqlink.qmname", None));
  Util.addIfNotNone(properties, "maxMsgSize", roleProperties.optString("websphere.sibmqlink.maxmsgsize", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.sibmqlink.description", None));
  print "Creating SIBMQLink with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SIBMQLink", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBMQLinkReceiverChannel":
        SIBMQLinkReceiverChannel.create(objid, curjsonobject);
      elif currole == "WebSphereSIBMQLinkSenderChannel":
        SIBMQLinkSenderChannel.create(objid, curjsonobject, parentconpath);
      elif currole == "WebSphereSIBPSBBrokerProfile":
        SIBPSBBrokerProfile.create(objid, curjsonobject);
  Util.popPathElement('SIBMQLink');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.uuid", None), "uuid","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.sequencewrap", None), "sequenceWrap","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.name", None), "name","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.initialstate", None), "initialState","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.targetuuid", None), "targetUuid","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.nonpersistentmessagespeed", None), "nonPersistentMessageSpeed","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.adoptable", None), "adoptable","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.heartbeat", None), "heartBeat","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.batchsize", None), "batchSize","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.qmname", None), "qmName","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.maxmsgsize", None), "maxMsgSize","SIBMQLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibmqlink.description", None), "description","SIBMQLink");
  if len(atts) != 0:
    print "Modifying SIBMQLink with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

  brokerProfiles = Util.parseConfigIdListAttribute(objid, 'brokerProfile', "SIBMQLink");
  for brokerProfile in brokerProfiles:
    Util.remove(brokerProfile);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBMQLinkReceiverChannel":
        SIBMQLinkReceiverChannel.create(objid, curjsonobject);
      elif currole == "WebSphereSIBMQLinkSenderChannel":
        SIBMQLinkSenderChannel.create(objid, curjsonobject, parentconpath);
      elif currole == "WebSphereSIBPSBBrokerProfile":
        SIBPSBBrokerProfile.create(objid, curjsonobject);

  Util.popPathElement('SIBMQLink');
