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

__name_att__ = "websphere.chain.name"

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'Chain');

  containmentpath = "%(parentconpath)sChain:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath);
  dict['conpath'] = containmentpath;
  return dict

def _export(objid, parentrespath):
  Util.pushPathElement('Chain')

  name = Util.getRequiredAttribute(objid, "name", 'Chain');


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

  roleProperties = JSONObject();

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

  i = 0;
  channels = Util.parseConfigIdListAttribute(objid, 'transportChannels', "Chain");
  for channel in channels:
    if len(channel) > 0:
      returndict = Util.createTypeFolder(respath, "Transport Channels", typeFolders, 1);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, TransportChannelRef._export(currespath, Util.getRequiredAttribute(channel, 'name', 'TransportChannel'), i));
      i = i + 1;

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



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

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

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    if parentid == None or len(parentid) == 0:
      raise Exception("Parent does not exist to create Chain on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;
"""



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  transportChannelRefDict = {};
  i = 0;
  for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
    currole = curjsonobject.getString('roleName');
    curname = curjsonobject.getString('name');
    if currole == "WebSphereTransportChannelRef":
      transChanRefRoleProperties = curjsonobject.getJSONObject("roleProperties");
      ordernum = transChanRefRoleProperties.getInt("websphere.transportchannelref.ordernum");
      transportChannelRefDict[ordernum] = curjsonobject;
      i = i + 1;

  for x in range(0, i):
    if not transportChannelRefDict.has_key(x):
      raise Exception("Incoherent Chain found. Missing Transport Channel Ref with order number %s" % x);
    curjsonobject = transportChannelRefDict[x];
    TransportChannelRef.create(objid, curjsonobject, 'transportChannels', transportNameToId);

  Util.popPathElement('Chain');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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