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

__name_att__ = None;


def _export(parentrespath, name, ordernum):
  Util.pushPathElement('TransportChannelRef')


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

  roleProperties = JSONObject();

  roleProperties.put("websphere.transportchannelref.name", name);
  roleProperties.put("websphere.transportchannelref.ordernum", ordernum);
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('TransportChannelRef');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.transportchannelref.name'):
    raise Exception("TransportChannelRef resource has property named websphere.transportchannelref.name!");

  channame = roleProperties.getString('websphere.transportchannelref.name')

  if not transportName2IdDict.has_key(channame):
    raise Exception("No TransportChannel with name %s defined for Admin Service!" % channame);

  chanid = transportName2IdDict[channame];

  properties = [];
  properties.append([parentAtt, chanid]);
  Log.debug(properties);
  Log.debug(parentid);
  print "Creating TransportChannelRef to %(id)s for attribute %(att)s" % { 'id':chanid, 'att':parentAtt };
  objid = Util.modify(parentid, properties);
  Log.debug("Finished Creating TransportChannelRef to %(id)s for attribute %(att)s" % { 'id':chanid, 'att':parentAtt });
  Util.popPathElement('TransportChannelRef');
