from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from RoutingActionRef import RoutingActionRef
from HTTPRequestHeaderActionRef import HTTPRequestHeaderActionRef
from HTTPResponseHeaderActionRef import HTTPResponseHeaderActionRef
from HTTPRequestCompressionActionRef import HTTPRequestCompressionActionRef
from HTTPResponseCompressionActionRef import HTTPResponseCompressionActionRef
from CachingActionRef import CachingActionRef
from RewritingActionRef import RewritingActionRef

__name_att__ = None;

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


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

  roleProperties = JSONObject();

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

  counterRoutingAction = 0;
  counterHTTPRequestHeaderAction = 0;
  counterHTTPResponseHeaderActionName = 0;
  counterHTTPRequestCompressionAction = 0;
  counterHTTPResponseCompressionAction = 0;
  counterCachingAction = 0;
  counterRewritingAction = 0;
  proxyActionRefs = Util.parseConfigIdListAttribute(objid, 'enabledProxyActions',"ProxyRuleExpression");
  for proxyActionRef in proxyActionRefs:
    if proxyActionRef is not None and len(proxyActionRef) > 0:
      if proxyActionRef.find("#RoutingAction") != -1:
        returndict = Util.createTypeFolder(respath, "RoutingActionRef", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        routingActionName = Util.getOptionalAttribute(proxyActionRef, "name", "RoutingAction");
        if routingActionName == None or len(routingActionName) == 0:
          routingActionName = ("Routing Action Ref%s" % counterRoutingAction)
        else:
          routingActionName = (routingActionName + " - " + "Routing Action Ref%s" % counterRoutingAction);
        Util.addAllFromExport(extraObjects, RoutingActionRef._export(proxyActionRef, currespath, routingActionName));
        counterRoutingAction = counterRoutingAction + 1;
      elif proxyActionRef.find("#HTTPRequestHeaderAction") != -1:
        returndict = Util.createTypeFolder(respath, "HTTPRequestHeaderActionRef", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        httpRequestHeaderActionName = Util.getOptionalAttribute(proxyActionRef, "name", "HTTPRequestHeaderAction");
        if httpRequestHeaderActionName == None or len(httpRequestHeaderActionName) == 0:
          httpRequestHeaderActionName = ("HTTP Request Header Action Ref%s" % counterHTTPRequestHeaderAction)
        else:
          httpRequestHeaderActionName = (httpRequestHeaderActionName + " - " + "HTTP Request Header Action Ref%s" % counterHTTPRequestHeaderAction);
        Util.addAllFromExport(extraObjects, HTTPRequestHeaderActionRef._export(proxyActionRef, currespath, httpRequestHeaderActionName));
        counterHTTPRequestHeaderAction = counterHTTPRequestHeaderAction + 1;
      elif proxyActionRef.find("#HTTPResponseHeaderAction") != -1:
        returndict = Util.createTypeFolder(respath, "HTTPResponseHeaderActionRef", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        httpResponseHeaderActionName = Util.getOptionalAttribute(proxyActionRef, "name", "HTTPResponseHeaderAction");
        if httpResponseHeaderActionName == None or len(httpResponseHeaderActionName) == 0:
          httpResponseHeaderActionName = ("HTTP Response Header Action Ref%s" % counterHTTPResponseHeaderActionName)
        else:
          httpResponseHeaderActionName = (httpResponseHeaderActionName + " - " + "HTTP Response Header Action Ref%s" % counterHTTPResponseHeaderActionName);
        Util.addAllFromExport(extraObjects, HTTPResponseHeaderActionRef._export(proxyActionRef, currespath, httpResponseHeaderActionName));
        counterHTTPResponseHeaderActionName = counterHTTPResponseHeaderActionName + 1;
      elif proxyActionRef.find("#HTTPRequestCompressionAction") != -1:
        returndict = Util.createTypeFolder(respath, "HTTPRequestCompressionActionRef", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        httpRequestCompressionActionName = Util.getOptionalAttribute(proxyActionRef, "name", "HTTPRequestCompressionAction");
        if httpRequestCompressionActionName == None or len(httpRequestCompressionActionName) == 0:
          httpRequestCompressionActionName = ("HTTP Request Compression Action Ref%s" % counterHTTPRequestCompressionAction)
        else:
          httpRequestCompressionActionName = (httpRequestCompressionActionName + " - " + "HTTP Request Compression Action Ref%s" % counterHTTPRequestCompressionAction);
        Util.addAllFromExport(extraObjects, HTTPRequestCompressionActionRef._export(proxyActionRef, currespath, httpRequestCompressionActionName));
        counterHTTPRequestCompressionAction = counterHTTPRequestCompressionAction + 1;
      elif proxyActionRef.find("#HTTPResponseCompressionAction") != -1:
        returndict = Util.createTypeFolder(respath, "HTTPResponseCompressionActionRef", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        httpResponseCompressionActionName = Util.getOptionalAttribute(proxyActionRef, "name", "HTTPResponseCompressionAction");
        if httpResponseCompressionActionName == None or len(httpResponseCompressionActionName) == 0:
          httpResponseCompressionActionName = ("HTTP Response Compression Action Ref%s" % counterHTTPResponseCompressionAction)
        else:
          httpResponseCompressionActionName = (httpResponseCompressionActionName + " - " + "HTTP Response Compression Action Ref%s" % counterHTTPResponseCompressionAction);
        Util.addAllFromExport(extraObjects, HTTPResponseCompressionActionRef._export(proxyActionRef, currespath, httpResponseCompressionActionName));
        counterHTTPResponseCompressionAction = counterHTTPResponseCompressionAction + 1;
      elif proxyActionRef.find("#CachingAction") != -1:
        returndict = Util.createTypeFolder(respath, "CachingActionRef", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        cachingActionName = Util.getOptionalAttribute(proxyActionRef, "name", "CachingAction");
        if cachingActionName == None or len(cachingActionName) == 0:
          cachingActionName = ("Caching Action Ref%s" % counterCachingAction)
        else:
          cachingActionName = (cachingActionName + " - " + "Caching Action Ref%s" % counterCachingAction);
        Util.addAllFromExport(extraObjects, CachingActionRef._export(proxyActionRef, currespath, cachingActionName));
        counterCachingAction = counterCachingAction + 1;
      elif proxyActionRef.find("#RewritingAction") != -1:
        returndict = Util.createTypeFolder(respath, "RewritingActionRef", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        rewritingActionName = Util.getOptionalAttribute(proxyActionRef, "name", "RewritingAction");
        if rewritingActionName == None or len(rewritingActionName) == 0:
          rewritingActionName = ("Rewriting Action Ref%s" % counterRewritingAction)
        else:
          rewritingActionName = (rewritingActionName + " - " + "Rewriting Action Ref%s" % counterRewritingAction);
        Util.addAllFromExport(extraObjects, RewritingActionRef._export(proxyActionRef, currespath, rewritingActionName));
        counterRewritingAction = counterRewritingAction + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereRoutingActionRef":
        RoutingActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderActionRef":
        HTTPRequestHeaderActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseHeaderActionRef":
        HTTPResponseHeaderActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestCompressionActionRef":
        HTTPRequestCompressionActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseCompressionActionRef":
        HTTPResponseCompressionActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereCachingActionRef":
        CachingActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereRewritingActionRef":
        RewritingActionRef.doImport(objid, curjsonobject);
  Util.popPathElement('ProxyRuleExpression');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  enabledProxyActions = Util.parseConfigIdListAttribute(objid, 'enabledProxyActions',"ProxyRuleExpression");
  for enabledProxyAction in enabledProxyActions:
    if len(enabledProxyAction) > 0:
      Util.remove(enabledProxyAction);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereRoutingActionRef":
        RoutingActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderActionRef":
        HTTPRequestHeaderActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseHeaderActionRef":
        HTTPResponseHeaderActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestCompressionActionRef":
        HTTPRequestCompressionActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseCompressionActionRef":
        HTTPResponseCompressionActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereCachingActionRef":
        CachingActionRef.doImport(objid, curjsonobject);
      elif currole == "WebSphereRewritingActionRef":
        RewritingActionRef.doImport(objid, curjsonobject);

  Util.popPathElement('ProxyRuleExpression');
