from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SIBDestinationDefault import SIBDestinationDefault
from SIBVirtualGatewayLink import SIBVirtualGatewayLink
from SIBVirtualMQLink import SIBVirtualMQLink
from SIBForeignBusRef import SIBForeignBusRef

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibforeignbus.name", objid, "name","SIBForeignBus");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibforeignbus.uuid", objid, "uuid","SIBForeignBus");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibforeignbus.description", objid, "description","SIBForeignBus");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibforeignbus.sendallowed", objid, "sendAllowed","SIBForeignBus");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  destinationDefault = Util.getOptionalAttribute(objid, 'destinationDefault',"SIBForeignBus");
  if destinationDefault is not None and len(destinationDefault) > 0:
    returndict = Util.createTypeFolder(respath, "SIBDestinationDefault", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, SIBDestinationDefault._export(destinationDefault, currespath, "SIB Destination Default"));

  virtualLink = Util.getOptionalAttribute(objid, 'virtualLink',"SIBForeignBus");
  if virtualLink is not None and len(virtualLink) > 0:
    if virtualLink.find("#SIBVirtualGatewayLink_") > 0:
      returndict = Util.createTypeFolder(respath, "SIBVirtualGatewayLink", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBVirtualGatewayLink._export(virtualLink, currespath, "SIB Virtual Gateway Link"));
    elif virtualLink.find("#SIBVirtualMQLink_") > 0:
      returndict = Util.createTypeFolder(respath, "SIBVirtualMQLink", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBVirtualMQLink._export(virtualLink, currespath, "SIB Virtual MQ Link"));

  nextHop = Util.getOptionalAttribute(objid, 'nextHop',"SIBForeignBus");
  if nextHop is not None and len(nextHop) > 0:
    returndict = Util.createTypeFolder(respath, "SIBForeignBusRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    nextHopName = Util.getRequiredAttribute(nextHop, "name", "SIBForeignBus");
    Util.addAllFromExport(extraObjects, SIBForeignBusRef._export(nextHop, currespath, nextHopName));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.sibforeignbus.name", None));
  Util.addIfNotNone(properties, "uuid", roleProperties.optString("websphere.sibforeignbus.uuid", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.sibforeignbus.description", None));
  Util.addIfNotNone(properties, "sendAllowed", roleProperties.optString("websphere.sibforeignbus.sendallowed", None));
  print "Creating SIBForeignBus with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SIBForeignBus", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBDestinationDefault":
        SIBDestinationDefault.create(objid, curjsonobject);
      elif currole == "WebSphereSIBVirtualGatewayLink":
        SIBVirtualGatewayLink.create(objid, curjsonobject);
      elif currole == "WebSphereSIBVirtualMQLink":
        SIBVirtualMQLink.create(objid, curjsonobject);
      elif currole == "WebSphereSIBForeignBusRef":
        SIBForeignBusRef.doImport(objid, curjsonobject);
  Util.popPathElement('SIBForeignBus');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibforeignbus.name", None), "name","SIBForeignBus");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibforeignbus.uuid", None), "uuid","SIBForeignBus");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibforeignbus.description", None), "description","SIBForeignBus");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibforeignbus.sendallowed", None), "sendAllowed","SIBForeignBus");
  if len(atts) != 0:
    print "Modifying SIBForeignBus with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBDestinationDefault":
        SIBDestinationDefault.create(objid, curjsonobject);
      elif currole == "WebSphereSIBVirtualGatewayLink":
        SIBVirtualGatewayLink.create(objid, curjsonobject);
      elif currole == "WebSphereSIBVirtualMQLink":
        SIBVirtualMQLink.create(objid, curjsonobject);
      elif currole == "WebSphereSIBForeignBusRef":
        SIBForeignBusRef.doImport(objid, curjsonobject);

  Util.popPathElement('SIBForeignBus');
