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

__name_att__ = "websphere.tcpinboundchannel.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sTCPInboundChannel:%(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('TCPInboundChannel')

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tcpinboundchannel.maxopenconnections", objid, "maxOpenConnections","TCPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tcpinboundchannel.name", objid, "name","TCPInboundChannel");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.tcpinboundchannel.hostnameincludelist", objid, "hostNameIncludeList","TCPInboundChannel");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.tcpinboundchannel.hostnameexcludelist", objid, "hostNameExcludeList","TCPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tcpinboundchannel.endpointname", objid, "endPointName","TCPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tcpinboundchannel.inactivitytimeout", objid, "inactivityTimeout","TCPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tcpinboundchannel.discriminationweight", objid, "discriminationWeight","TCPInboundChannel");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.tcpinboundchannel.addressincludelist", objid, "addressIncludeList","TCPInboundChannel");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.tcpinboundchannel.addressexcludelist", objid, "addressExcludeList","TCPInboundChannel");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  threadPool = Util.getOptionalAttribute(objid, 'threadPool', 'TCPInboundChannel');
  if threadPool is not None and len(threadPool) > 0:
    threadPoolName = Util.getRequiredAttribute(threadPool, 'name', 'ThreadPool');
    returndict = Util.createTypeFolder(respath, 'ThreadPool', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ThreadPoolRef._export(currespath, threadPoolName, 'Thread Pool'));

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"TCPInboundChannel");
    
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('TCPInboundChannel');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.tcpinboundchannel.name"):
    raise Exception("Resource role properties does not contain websphere.tcpinboundchannel.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 TCPInboundChannel on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "maxOpenConnections", roleProperties.optString("websphere.tcpinboundchannel.maxopenconnections", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.tcpinboundchannel.name", None));
  Util.addPathProperty(properties, "hostNameIncludeList", roleProperties.optString("websphere.tcpinboundchannel.hostnameincludelist", None));
  Util.addPathProperty(properties, "hostNameExcludeList", roleProperties.optString("websphere.tcpinboundchannel.hostnameexcludelist", None));
  Util.addIfNotNone(properties, "endPointName", roleProperties.optString("websphere.tcpinboundchannel.endpointname", None));
  Util.addIfNotNone(properties, "inactivityTimeout", roleProperties.optString("websphere.tcpinboundchannel.inactivitytimeout", None));
  Util.addIfNotNone(properties, "discriminationWeight", roleProperties.optString("websphere.tcpinboundchannel.discriminationweight", None));
  Util.addPathProperty(properties, "addressIncludeList", roleProperties.optString("websphere.tcpinboundchannel.addressincludelist", None));
  Util.addPathProperty(properties, "addressExcludeList", roleProperties.optString("websphere.tcpinboundchannel.addressexcludelist", None));
  print "Creating TCPInboundChannel with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("TCPInboundChannel", parentid, properties);

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if propertyObject == 0:
        if currole == "WebSphereThreadPoolRef":
          ThreadPoolRef.create(objid, curjsonobject, 'threadPool', threadPoolLookupPath);
  Util.popPathElement('TCPInboundChannel');

  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.maxopenconnections", None), "maxOpenConnections","TCPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.name", None), "name","TCPInboundChannel");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.hostnameincludelist", None), "hostNameIncludeList","TCPInboundChannel");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.hostnameexcludelist", None), "hostNameExcludeList","TCPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.endpointname", None), "endPointName","TCPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.inactivitytimeout", None), "inactivityTimeout","TCPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.discriminationweight", None), "discriminationWeight","TCPInboundChannel");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.addressincludelist", None), "addressIncludeList","TCPInboundChannel");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.tcpinboundchannel.addressexcludelist", None), "addressExcludeList","TCPInboundChannel");
  if len(atts) != 0:
    print "Modifying TCPInboundChannel with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if propertyObject == 0:
        if currole == "WebSphereThreadPoolRef":
          ThreadPoolRef.create(objid, curjsonobject, 'threadPool', threadPoolLookupPath);
  Util.popPathElement('TCPInboundChannel');
