from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SIBLinkRef import SIBLinkRef
from SIBTopicSpaceMapping import SIBTopicSpaceMapping

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibvirtualgatewaylink.inbounduserid", objid, "inboundUserid","SIBVirtualGatewayLink");
  # default name from WebSphere contains a colon, which WebSphere does not accept when manually creating/updating
  name = Util.getRequiredAttribute(objid, "name", 'SIBVirtualGatewayLink');
  name = Util.replaceColonWithDash(name);
  Util.addToJsonIfNotNone(roleProperties, 'websphere.sibvirtualgatewaylink.name', name);
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibvirtualgatewaylink.uuid", objid, "uuid","SIBVirtualGatewayLink");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibvirtualgatewaylink.outbounduserid", objid, "outboundUserid","SIBVirtualGatewayLink");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  linkRefs = Util.parseConfigIdListAttribute(objid, 'linkRef',"SIBVirtualGatewayLink");
  for linkRef in linkRefs:
    if len(linkRef) > 0:
      returndict = Util.createTypeFolder(respath, "SIBLinkRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      linkRefName = Util.getRequiredAttribute(linkRef, "name", "SIBLinkRef");
      Util.addAllFromExport(extraObjects, SIBLinkRef._export(linkRef, currespath, linkRefName));

  topicSpaceMapping = Util.getRequiredAttribute(objid, 'topicSpaceMapping',"SIBVirtualGatewayLink");
  if topicSpaceMapping is not None and len(topicSpaceMapping) > 0:
    returndict = Util.createTypeFolder(respath, "SIBTopicSpaceMapping", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, SIBTopicSpaceMapping._export(topicSpaceMapping, currespath, "SIB Topic Space Mapping")); 

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "inboundUserid", roleProperties.optString("websphere.sibvirtualgatewaylink.inbounduserid", None));
  Util.addIfNotNone(properties, "name", Util.replaceColonWithDash(roleProperties.optString("websphere.sibvirtualgatewaylink.name", None)));
  Util.addIfNotNone(properties, "uuid", roleProperties.optString("websphere.sibvirtualgatewaylink.uuid", None));
  Util.addIfNotNone(properties, "outboundUserid", roleProperties.optString("websphere.sibvirtualgatewaylink.outbounduserid", None));
  print "Creating SIBVirtualGatewayLink with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SIBVirtualGatewayLink", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBLinkRef":
        SIBLinkRef.create(objid, curjsonobject);
      elif currole == "WebSphereSIBTopicSpaceMapping":
        SIBTopicSpaceMapping.create(objid, curjsonobject);
  Util.popPathElement('SIBVirtualGatewayLink');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibvirtualgatewaylink.inbounduserid", None), "inboundUserid","SIBVirtualGatewayLink");
  Util.addAttIfChanged(objid, atts, Util.replaceColonWithDash(roleProperties.optString("websphere.sibvirtualgatewaylink.name", None)), "name","SIBVirtualGatewayLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibvirtualgatewaylink.uuid", None), "uuid","SIBVirtualGatewayLink");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibvirtualgatewaylink.outbounduserid", None), "outboundUserid","SIBVirtualGatewayLink");
  if len(atts) != 0:
    print "Modifying SIBVirtualGatewayLink with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  linkRefs = Util.parseConfigIdListAttribute(objid, 'linkRef',"SIBVirtualGatewayLink");
  for linkRef in linkRefs:
    if len(linkRef) > 0:
      Util.remove(linkRef);

  topicSpaceMapping = Util.getRequiredAttribute(objid, 'topicSpaceMapping',"SIBVirtualGatewayLink");
  if topicSpaceMapping is not None and len(topicSpaceMapping) > 0:
    Util.remove(topicSpaceMapping);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBLinkRef":
        SIBLinkRef.create(objid, curjsonobject);
      elif currole == "WebSphereSIBTopicSpaceMapping":
        SIBTopicSpaceMapping.create(objid, curjsonobject);

  Util.popPathElement('SIBVirtualGatewayLink');
