from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from EndPoint import EndPoint
from OverlayEndpoint import OverlayEndpoint
from utilities import Util
from Property import Property

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmstransport.sslenabled", objid, "sslEnabled","JMSTransport");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmstransport.sslconfig", objid, "sslConfig","JMSTransport");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmstransport.external", objid, "external","JMSTransport");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"JMSTransport");

  address = Util.getOptionalAttribute(objid, 'address', 'JMSTransport');
  if address is not None and len(address) > 0:
    if address.find("#EndPoint_") != -1:
      returndict = Util.createTypeFolder(respath, "EndPoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, EndPoint._export(address, currespath, 'address'));
    elif address.find("#OverlayEndpoint_") != -1:
      returndict = Util.createTypeFolder(respath, "OverlayEndpoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, OverlayEndpoint._export(address, currespath, 'address'));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "sslEnabled", roleProperties.optString("websphere.jmstransport.sslenabled", None));
  Util.addIfNotNone(properties, "sslConfig", roleProperties.optString("websphere.jmstransport.sslconfig", None));
  Util.addIfNotNone(properties, "external", roleProperties.optString("websphere.jmstransport.external", None));
  print "Creating JMSTransport with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("JMSTransport", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereEndPoint":
          EndPoint.create(objid, curjsonobject, 'address');
        elif currole == "WebSphereOverlayEndpoint":
          OverlayEndpoint.create(objid, curjsonobject, 'address');
  Util.popPathElement('JMSTransport');


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmstransport.sslenabled", None), "sslEnabled","JMSTransport");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmstransport.sslconfig", None), "sslConfig","JMSTransport");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmstransport.external", None), "external","JMSTransport");
  if len(atts) != 0:
    print "Modifying JMSTransport with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"JMSTransport");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereEndPoint":
          EndPoint.create(objid, curjsonobject, 'address');
        elif currole == "WebSphereOverlayEndpoint":
          OverlayEndpoint.create(objid, curjsonobject, 'address');
  Util.popPathElement('JMSTransport');
