from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from WASConfLog import Log;
from utilities import Util

__name_att__ = "websphere.sibforeignbusref.name"

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

  if name == "":
    name = Util.getRequiredAttribute(objid, "name", "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 SIBForeignBusRef");
  exportedObject.put("roleName", "WebSphereSIBForeignBusRef");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibforeignbusref.name", objid, "name","SIBForeignBus");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('SIBForeignBusRef');
  return result;


def doImport(parentid, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("SIBForeignBusRef resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.sibforeignbusref.name"):
    raise Exception("Resource role properties does not contain websphere.sibforeignbusref.name!");

  referencedSIBForeignBusName = roleProperties.optString("websphere.sibforeignbusref.name", None);

  # get the name of the parent SIBus, so we may limit the scope of our search to
  # only SIBForeignBuses that belong to the parent SIBus.
  # parentId format: MyTestForeignBus(cells/CloudBurstCell_1/buses/MyTestSIBus|sib-bus.xml#SIBForeignBus_1431090851030)
  parentSIBusName = parentid.split('/buses/')[1].split('|')[0];

  containmentPath = "/SIBus:" + parentSIBusName + "/SIBForeignBus:" + referencedSIBForeignBusName + "/";
  referencedSIBForeignBus = Util.getid(containmentPath);
  if referencedSIBForeignBus == None or len(referencedSIBForeignBus) == 0:
    raise Exception("Could not find referenced SIBForeignBus with name " + referencedSIBForeignBusName + "for SIBForeignBus " + parentid + ".");
  Util.pushPathElement("SIBus");
  Util.pushPathElement("SIBForeignBus");
  Util.modify(parentid, [['nextHop', referencedSIBForeignBus]]);
  Util.popPathElement("SIBForeignBus");
  Util.popPathElement("SIBus");

