from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Chain import Chain
from TransportChannelFactory import TransportChannelFactory
from TransportChannel import TransportChannel
from utilities import Util
from Property import Property

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.transportchannelservice.enable", objid, "enable","TransportChannelService");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

  extraObjects = TransportChannelFactory.exportTransportChannelFactories(objid, respath, extraObjects, typeFolders, 'factories', "TransportChannelService");

  extraObjects = TransportChannel.exportTransportChannels(objid, respath, extraObjects, typeFolders, 'transportChannels', "TransportChannelService");

  chains = Util.parseConfigIdListAttribute(objid, 'chains',"TransportChannelService");
  for chain in chains:
    if len(chain) > 0:
      returndict = Util.createTypeFolder(respath, "Chain", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, Chain._export(chain, currespath));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.transportchannelservice.enable", None));
  print "Creating TransportChannelService with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("TransportChannelService", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);

  TransportChannelFactory.removeTransportChannelFactories(objid, 'factories', "TransportChannelService");

  TransportChannel.removeTransportChannels(objid, 'transportChannels', "TransportChannelService");


  chainjsonobjects = [];
  transportNameToId = {};
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      factoryObject = 0;
      channelObject = 0;
      factoryObject = TransportChannelFactory.createObjIfRole(objid, curjsonobject, currole);
      if (factoryObject == 0):
        channelObject = TransportChannel.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
        if (channelObject is None or len(channelObject) < 1):
          if currole == "WebSphereChain":
            chainjsonobjects.append(curjsonobject);
        else:
          transportNameToId[Util.getRequiredAttribute(channelObject, 'name', 'TransportChannel')] = channelObject;

  # we must ensure all transports channels are created before we can create Chains as they can contain references to the channels
  for curjsonobject in chainjsonobjects:
    Chain.create(objid, curjsonobject, transportNameToId);
  Util.popPathElement('TransportChannelService');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  chains = Util.parseConfigIdListAttribute(objid, 'chains',"TransportChannelService");
  for chain in chains:
    if len(chain) > 0:
      Util.remove(chain);

  TransportChannelFactory.removeTransportChannelFactories(objid, 'factories', "TransportChannelService");

  TransportChannel.removeTransportChannels(objid, 'transportChannels', "TransportChannelService");

  chainjsonobjects = [];
  transportNameToId = {};
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = 0;
      factoryObject = 0;
      channelObject = 0;
      propertyObject = propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        factoryObject = TransportChannelFactory.createObjIfRole(objid, curjsonobject, currole);
        if (factoryObject == 0):
          channelObject = TransportChannel.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
        if (channelObject is None or len(channelObject) < 1):
            if currole == "WebSphereChain":
              Chain.create(objid, curjsonobject);
            chainjsonobjects.append(curjsonobject);
        else:
          transportNameToId[Util.getRequiredAttribute(channelObject, 'name', 'TransportChannel')] = channelObject;

  # we must ensure all transports channels are created before we can create Chains as they can contain references to the channels
  for curjsonobject in chainjsonobjects:
    Chain.create(objid, curjsonobject, transportNameToId, threadPoolLookupPath);
  Util.popPathElement('TransportChannelService');
