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

__name_att__ = "websphere.httpinboundchannel.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.enablelogging", objid, "enableLogging","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.name", objid, "name","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.readtimeout", objid, "readTimeout","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.maxfieldsize", objid, "maxFieldSize","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.usechannelaccessloggingsettings", objid, "useChannelAccessLoggingSettings","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.maxrequestmessagebodysize", objid, "maxRequestMessageBodySize","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.maximumpersistentrequests", objid, "maximumPersistentRequests","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.discriminationweight", objid, "discriminationWeight","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.persistenttimeout", objid, "persistentTimeout","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.maxheaders", objid, "maxHeaders","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.keepalive", objid, "keepAlive","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.writetimeout", objid, "writeTimeout","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.usechannelfrcaloggingsettings", objid, "useChannelFRCALoggingSettings","HTTPInboundChannel");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannel.usechannelerrorloggingsettings", objid, "useChannelErrorLoggingSettings","HTTPInboundChannel");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"HTTPInboundChannel");

  httpInboundChannelLogging = Util.getOptionalAttribute(objid, 'httpInboundChannelLogging', 'HTTPInboundChannel');
  if httpInboundChannelLogging is not None and len(httpInboundChannelLogging) > 0:
    returndict = Util.createTypeFolder(respath, "HTTPInboundChannelLogging", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, HTTPInboundChannelLogging._export(httpInboundChannelLogging, currespath, 'HTTPInboundChannel'));

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "enableLogging", roleProperties.optString("websphere.httpinboundchannel.enablelogging", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.httpinboundchannel.name", None));
  Util.addIfNotNone(properties, "readTimeout", roleProperties.optString("websphere.httpinboundchannel.readtimeout", None));
  Util.addIfNotNone(properties, "maxFieldSize", roleProperties.optString("websphere.httpinboundchannel.maxfieldsize", None));
  Util.addIfNotNone(properties, "useChannelAccessLoggingSettings", roleProperties.optString("websphere.httpinboundchannel.usechannelaccessloggingsettings", None));
  Util.addIfNotNone(properties, "maxRequestMessageBodySize", roleProperties.optString("websphere.httpinboundchannel.maxrequestmessagebodysize", None));
  Util.addIfNotNone(properties, "maximumPersistentRequests", roleProperties.optString("websphere.httpinboundchannel.maximumpersistentrequests", None));
  Util.addIfNotNone(properties, "discriminationWeight", roleProperties.optString("websphere.httpinboundchannel.discriminationweight", None));
  Util.addIfNotNone(properties, "persistentTimeout", roleProperties.optString("websphere.httpinboundchannel.persistenttimeout", None));
  Util.addIfNotNone(properties, "maxHeaders", roleProperties.optString("websphere.httpinboundchannel.maxheaders", None));
  Util.addIfNotNone(properties, "keepAlive", roleProperties.optString("websphere.httpinboundchannel.keepalive", None));
  Util.addIfNotNone(properties, "writeTimeout", roleProperties.optString("websphere.httpinboundchannel.writetimeout", None));
  Util.addIfNotNone(properties, "useChannelFRCALoggingSettings", roleProperties.optString("websphere.httpinboundchannel.usechannelfrcaloggingsettings", None));
  Util.addIfNotNone(properties, "useChannelErrorLoggingSettings", roleProperties.optString("websphere.httpinboundchannel.usechannelerrorloggingsettings", None));
  print "Creating HTTPInboundChannel with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("HTTPInboundChannel", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereHTTPInboundChannelLogging":
        HTTPInboundChannelLogging.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('HTTPInboundChannel');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.enablelogging", None), "enableLogging","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.name", None), "name","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.readtimeout", None), "readTimeout","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.maxfieldsize", None), "maxFieldSize","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.usechannelaccessloggingsettings", None), "useChannelAccessLoggingSettings","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.maxrequestmessagebodysize", None), "maxRequestMessageBodySize","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.maximumpersistentrequests", None), "maximumPersistentRequests","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.discriminationweight", None), "discriminationWeight","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.persistenttimeout", None), "persistentTimeout","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.maxheaders", None), "maxHeaders","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.keepalive", None), "keepAlive","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.writetimeout", None), "writeTimeout","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.usechannelfrcaloggingsettings", None), "useChannelFRCALoggingSettings","HTTPInboundChannel");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannel.usechannelerrorloggingsettings", None), "useChannelErrorLoggingSettings","HTTPInboundChannel");
  if len(atts) != 0:
    print "Modifying HTTPInboundChannel with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereHTTPInboundChannelLogging":
        HTTPInboundChannelLogging.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('HTTPInboundChannel');
