from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from HTTPResponseHeaderAction import HTTPResponseHeaderAction
from RoutingAction import RoutingAction
from HTTPRequestCompressionAction import HTTPRequestCompressionAction
from HTTPResponseCompressionAction import HTTPResponseCompressionAction

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httprequestheaderaction.name", objid, "name","HTTPRequestHeaderAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httprequestheaderaction.headermodifyaction", objid, "headerModifyAction","HTTPRequestHeaderAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httprequestheaderaction.headervalueexpression", objid, "headerValueExpression","HTTPRequestHeaderAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httprequestheaderaction.headername", objid, "headerName","HTTPRequestHeaderAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httprequestheaderaction.headervalue", objid, "headerValue","HTTPRequestHeaderAction");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.httprequestheaderaction.methodnames", objid, "methodNames","HTTPRequestHeaderAction");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  httpCompressionAction = Util.getOptionalAttribute(objid, 'HTTPCompressionAction',"HTTPRequestHeaderAction");
  if httpCompressionAction is not None and len(httpCompressionAction) > 0:
    if httpCompressionAction.find("#HTTPRequestCompressionAction_") != -1:
      returndict = Util.createTypeFolder(respath, "HTTPRequestCompressionAction", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      httpCompressionActionName = Util.getOptionalAttribute(httpCompressionAction, "name", "HTTPRequestCompressionAction");
      if httpCompressionActionName == None or len(httpCompressionActionName) == 0:
        httpCompressionActionName = ("HTTP Request Compression Action")
      Util.addAllFromExport(extraObjects, HTTPRequestCompressionAction._export(httpCompressionAction, currespath, httpCompressionActionName));
    elif httpCompressionAction.find("#HTTPResponseCompressionAction_") != -1:
      returndict = Util.createTypeFolder(respath, "HTTPResponseCompressionAction", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      httpCompressionActionName = Util.getOptionalAttribute(httpCompressionAction, "name", "HTTPResponseCompressionAction");
      if httpCompressionActionName == None or len(httpCompressionActionName) == 0:
        httpCompressionActionName = ("HTTP Response Compression Action")
      Util.addAllFromExport(extraObjects, HTTPResponseCompressionAction._export(httpCompressionAction, currespath, httpCompressionActionName));

  httpRequestHeaderAction = Util.getOptionalAttribute(objid, 'HTTPHeaderRequestAction', 'HTTPRequestHeaderAction');
  if httpRequestHeaderAction is not None and len(httpRequestHeaderAction) > 0:
    returndict = Util.createTypeFolder(respath, "HTTPRequestHeaderAction", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    httpRequestHeaderActionName = Util.getOptionalAttribute(httpRequestHeaderAction, "name", "HTTPRequestHeaderAction");
    if httpRequestHeaderActionName == None or len(httpRequestHeaderActionName) == 0:
      httpRequestHeaderActionName = ("HTTP Request Header Action")
    Util.addAllFromExport(extraObjects, _export(httpRequestHeaderAction, currespath, httpRequestHeaderActionName));

  httpResponseHeaderAction = Util.getOptionalAttribute(objid, 'HTTPHeaderResponseAction', 'HTTPRequestHeaderAction');
  if httpResponseHeaderAction is not None and len(httpResponseHeaderAction) > 0:
    returndict = Util.createTypeFolder(respath, "HTTPResponseHeaderAction", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    httpResponseHeaderActionName = Util.getOptionalAttribute(httpResponseHeaderAction, "name", "HTTPResponseHeaderAction");
    if httpResponseHeaderActionName == None or len(httpResponseHeaderActionName) == 0:
      httpResponseHeaderActionName = ("HTTP Response Header Action")
    Util.addAllFromExport(extraObjects, HTTPResponseHeaderAction._export(httpResponseHeaderAction, currespath, httpResponseHeaderActionName));

  routingAction = Util.getOptionalAttribute(objid, 'routingAction', 'HTTPRequestHeaderAction');
  if routingAction is not None and len(routingAction) > 0:
    returndict = Util.createTypeFolder(respath, "RoutingAction", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    routingActionName = Util.getOptionalAttribute(routingAction, "name", "RoutingAction");
    if routingActionName == None or len(routingActionName) == 0:
      routingActionName = ("Routing Action")
    Util.addAllFromExport(extraObjects, RoutingAction._export(routingAction, currespath, routingActionName));

  headerAction = Util.getOptionalAttribute(objid, 'headerAction',"HTTPRequestHeaderAction");
  if headerAction is not None and len(headerAction) > 0:
    if headerAction.find("#HTTPRequestHeaderAction_") != -1:
      returndict = Util.createTypeFolder(respath, "HTTPRequestHeaderAction", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      httpRequestHeaderActionName = Util.getOptionalAttribute(headerAction, "name", "HTTPRequestHeaderAction");
      if httpRequestHeaderActionName == None or len(httpRequestHeaderActionName) == 0:
        httpRequestHeaderActionName = ("HTTP Request Header Action");
      Util.addAllFromExport(extraObjects, _export(headerAction, currespath, httpRequestHeaderActionName));
    elif headerAction.find("#HTTPResponseHeaderAction_") != -1:
      returndict = Util.createTypeFolder(respath, "HTTPResponseHeaderAction", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      httpResponseHeaderActionName = Util.getOptionalAttribute(headerAction, "name", "HTTPResponseHeaderAction");
      if httpResponseHeaderActionName == None or len(httpResponseHeaderActionName) == 0:
        httpResponseHeaderActionName = ("HTTP Response Header Action");
      Util.addAllFromExport(extraObjects, HTTPResponseHeaderAction._export(headerAction, currespath, httpResponseHeaderActionName));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.httprequestheaderaction.name", None));
  Util.addIfNotNone(properties, "headerModifyAction", roleProperties.optString("websphere.httprequestheaderaction.headermodifyaction", None));
  Util.addIfNotNone(properties, "headerValueExpression", roleProperties.optString("websphere.httprequestheaderaction.headervalueexpression", None));
  Util.addIfNotNone(properties, "headerName", roleProperties.optString("websphere.httprequestheaderaction.headername", None));
  Util.addIfNotNone(properties, "headerValue", roleProperties.optString("websphere.httprequestheaderaction.headervalue", None));
  Util.addPathProperty(properties, "methodNames", roleProperties.optString("websphere.httprequestheaderaction.methodnames", None));
  print "Creating HTTPRequestHeaderAction with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("HTTPRequestHeaderAction", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereHTTPResponseHeaderAction":
        HTTPResponseHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderAction":
        create(objid, curjsonobject);
      elif currole == "WebSphereRoutingAction":
        RoutingAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestCompressionAction":
        HTTPRequestCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseCompressionAction":
        HTTPResponseCompressionAction.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('HTTPRequestHeaderAction');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httprequestheaderaction.name", None), "name","HTTPRequestHeaderAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httprequestheaderaction.headermodifyaction", None), "headerModifyAction","HTTPRequestHeaderAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httprequestheaderaction.headervalueexpression", None), "headerValueExpression","HTTPRequestHeaderAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httprequestheaderaction.headername", None), "headerName","HTTPRequestHeaderAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httprequestheaderaction.headervalue", None), "headerValue","HTTPRequestHeaderAction");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.httprequestheaderaction.methodnames", None), "methodNames","HTTPRequestHeaderAction");
  if len(atts) != 0:
    print "Modifying HTTPRequestHeaderAction with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  httpCompressionAction = Util.getOptionalAttribute(objid, 'HTTPCompressionAction',"HTTPRequestHeaderAction");
  if httpCompressionAction is not None and len(httpCompressionAction) > 0:
    Util.remove(httpCompressionAction);

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

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereHTTPResponseHeaderAction":
        HTTPResponseHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderAction":
        create(objid, curjsonobject);
      elif currole == "WebSphereRoutingAction":
        RoutingAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestCompressionAction":
        HTTPRequestCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseCompressionAction":
        HTTPResponseCompressionAction.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('HTTPRequestHeaderAction');
