from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from ProxyAction import ProxyAction
from RoutingAction import RoutingAction
from HeaderAction import HeaderAction
from HTTPRequestHeaderAction import HTTPRequestHeaderAction
from HTTPResponseHeaderAction import HTTPResponseHeaderAction
from CompressionAction import CompressionAction
from HTTPRequestCompressionAction import HTTPRequestCompressionAction
from HTTPResponseCompressionAction import HTTPResponseCompressionAction
from CachingAction import CachingAction
from RewritingAction import RewritingAction
from ProxyRuleExpression import ProxyRuleExpression
from ProxyVirtualHost import ProxyVirtualHost
from ProxyVirtualHostRef import ProxyVirtualHostRef

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  counterRoutingAction = 0;
  counterHeaderAction = 0;
  counterHTTPRequestHeaderAction = 0;
  counterHTTPResponseHeaderActionName = 0;
  counterCompressionAction = 0;
  counterHTTPRequestCompressionAction = 0;
  counterHTTPResponseCompressionAction = 0;
  counterCachingAction = 0;
  counterRewritingAction = 0;
  proxyActions = Util.parseConfigIdListAttribute(objid, 'proxyActions',"ProxyVirtualHostConfig");
  for proxyAction in proxyActions:
    if proxyAction is not None and len(proxyAction) > 0:
      if proxyAction.find("#RoutingAction") != -1:
        returndict = Util.createTypeFolder(respath, "RoutingAction", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        routingActionName = Util.getOptionalAttribute(proxyAction, "name", "RoutingAction");
        if routingActionName == None or len(routingActionName) == 0:
          routingActionName = ("Routing Action%s" % counterRoutingAction)
        else:
          routingActionName = (routingActionName + " - " + "Routing Action%s" % counterRoutingAction);
        Util.addAllFromExport(extraObjects, RoutingAction._export(proxyAction, currespath, routingActionName));
        counterRoutingAction = counterRoutingAction + 1;
      elif proxyAction.find("#HeaderAction") != -1:
        returndict = Util.createTypeFolder(respath, "HeaderAction", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        headerActionName = Util.getOptionalAttribute(proxyAction, "name", "HeaderAction");
        if headerActionName == None or len(headerActionName) == 0:
          headerActionName = ("Header Action%s" % counterHeaderAction)
        else:
          headerActionName = (headerActionName + " - " + "Header Action%s" % counterHeaderAction);
        Util.addAllFromExport(extraObjects, RoutingAction._export(proxyAction, currespath, headerActionName));
        counterHeaderAction = counterHeaderAction + 1;
      elif proxyAction.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(proxyAction, "name", "HTTPRequestHeaderAction");
        if httpRequestHeaderActionName == None or len(httpRequestHeaderActionName) == 0:
          httpRequestHeaderActionName = ("HTTP Request Header Action%s" % counterHTTPRequestHeaderAction)
        else:
          httpRequestHeaderActionName = (httpRequestHeaderActionName + " - " + "HTTP Request Header Action%s" % counterHTTPRequestHeaderAction);
        Util.addAllFromExport(extraObjects, HTTPRequestHeaderAction._export(proxyAction, currespath, httpRequestHeaderActionName));
        counterHTTPRequestHeaderAction = counterHTTPRequestHeaderAction + 1;
      elif proxyAction.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(proxyAction, "name", "HTTPResponseHeaderAction");
        if httpResponseHeaderActionName == None or len(httpResponseHeaderActionName) == 0:
          httpResponseHeaderActionName = ("HTTP Response Header Action%s" % counterHTTPResponseHeaderActionName)
        else:
          httpResponseHeaderActionName = (httpResponseHeaderActionName + " - " + "HTTP Response Header Action%s" % counterHTTPResponseHeaderActionName);
        Util.addAllFromExport(extraObjects, HTTPResponseHeaderAction._export(proxyAction, currespath, httpResponseHeaderActionName));
        counterHTTPResponseHeaderActionName = counterHTTPResponseHeaderActionName + 1;
      elif proxyAction.find("#CompressionAction") != -1:
        returndict = Util.createTypeFolder(respath, "CompressionAction", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        compressionActionName = Util.getOptionalAttribute(proxyAction, "name", "CompressionAction");
        if compressionActionName == None or len(compressionActionName) == 0:
          compressionActionName = ("Compression Action%s" % counterCompressionAction)
        else:
          compressionActionName = (compressionActionName + " - " + "Compression Action%s" % counterCompressionAction);
        Util.addAllFromExport(extraObjects, CompressionAction._export(proxyAction, currespath, compressionActionName));
        counterCompressionAction = counterCompressionAction + 1;
      elif proxyAction.find("#HTTPRequestCompressionAction") != -1:
        returndict = Util.createTypeFolder(respath, "HTTPRequestCompressionAction", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        httpRequestCompressionActionName = Util.getOptionalAttribute(proxyAction, "name", "HTTPRequestCompressionAction");
        if httpRequestCompressionActionName == None or len(httpRequestCompressionActionName) == 0:
          httpRequestCompressionActionName = ("HTTP Request Compression Action%s" % counterHTTPRequestCompressionAction)
        else:
          httpRequestCompressionActionName = (httpRequestCompressionActionName + " - " + "HTTP Request Compression Action%s" % counterHTTPRequestCompressionAction);
        Util.addAllFromExport(extraObjects, HTTPRequestCompressionAction._export(proxyAction, currespath, httpRequestCompressionActionName));
        counterHTTPRequestCompressionAction = counterHTTPRequestCompressionAction + 1;
      elif proxyAction.find("#HTTPResponseCompressionAction") != -1:
        returndict = Util.createTypeFolder(respath, "HTTPResponseCompressionAction", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        httpResponseCompressionActionName = Util.getOptionalAttribute(proxyAction, "name", "HTTPResponseCompressionAction");
        if httpResponseCompressionActionName == None or len(httpResponseCompressionActionName) == 0:
          httpResponseCompressionActionName = ("HTTP Response Compression Action%s" % counterHTTPResponseCompressionAction)
        else:
          httpResponseCompressionActionName = (httpResponseCompressionActionName + " - " + "HTTP Response Compression Action%s" % counterHTTPResponseCompressionAction);
        Util.addAllFromExport(extraObjects, HTTPResponseCompressionAction._export(proxyAction, currespath, httpResponseCompressionActionName));
        counterHTTPResponseCompressionAction = counterHTTPResponseCompressionAction + 1;
      elif proxyAction.find("#CachingAction") != -1:
        returndict = Util.createTypeFolder(respath, "CachingAction", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        cachingActionName = Util.getOptionalAttribute(proxyAction, "name", "CachingAction");
        if cachingActionName == None or len(cachingActionName) == 0:
          cachingActionName = ("Caching Action%s" % counterCachingAction)
        else:
          cachingActionName = (cachingActionName + " - " + "Caching Action%s" % counterCachingAction);
        Util.addAllFromExport(extraObjects, CachingAction._export(proxyAction, currespath, cachingActionName));
        counterCachingAction = counterCachingAction + 1;
      elif proxyAction.find("#RewritingAction") != -1:
        returndict = Util.createTypeFolder(respath, "RewritingAction", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        rewritingActionName = Util.getOptionalAttribute(proxyAction, "name", "RewritingAction");
        if rewritingActionName == None or len(rewritingActionName) == 0:
          rewritingActionName = ("Rewriting Action%s" % counterRewritingAction)
        else:
          rewritingActionName = (rewritingActionName + " - " + "Rewriting Action%s" % counterRewritingAction);
        Util.addAllFromExport(extraObjects, RewritingAction._export(proxyAction, currespath, rewritingActionName));
        counterRewritingAction = counterRewritingAction + 1;

  i = 0;
  proxyRuleExpressions = Util.parseConfigIdListAttribute(objid, 'proxyRuleExpressions',"ProxyVirtualHostConfig");
  for proxyRuleExpression in proxyRuleExpressions:
    if len(proxyRuleExpression) > 0:
      returndict = Util.createTypeFolder(respath, "ProxyRuleExpression", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      proxyRuleExpressionName = Util.getOptionalAttribute(proxyRuleExpression, "name", "ProxyRuleExpression");
      if proxyRuleExpressionName == None or len(proxyRuleExpressionName) == 0:
          proxyRuleExpressionName = ("Proxy Rule Exporession%s" % i)
      else:
        routingActionName = (proxyRuleExpressionName + " - " + "Proxy Rule Exporession%s" % i);
      Util.addAllFromExport(extraObjects, ProxyRuleExpression._export(proxyRuleExpression, currespath, proxyRuleExpressionName));
      i = i + 1;

  i = 0;
  proxyVirtualHosts = Util.parseConfigIdListAttribute(objid, 'proxyVirtualHosts',"ProxyVirtualHostConfig");
  for proxyVirtualHost in proxyVirtualHosts:
    if len(proxyVirtualHost) > 0:
      returndict = Util.createTypeFolder(respath, "ProxyVirtualHost", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ProxyVirtualHost._export(proxyVirtualHost, currespath, "Proxy Virtual Host%s" % i));
      i = i + 1;

  proxyVirtualHostRefs = Util.parseConfigIdListAttribute(objid, 'enabledProxyVirtualHosts', 'ProxyVirtualHostConfig');
  for proxyVirtualHostRef in proxyVirtualHostRefs:
    if proxyVirtualHostRef is not None and len(proxyVirtualHostRef) > 0:
      returndict = Util.createTypeFolder(respath, "ProxyVirtualHostRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ProxyVirtualHostRef._export(proxyVirtualHostRef, currespath));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  print "Creating ProxyVirtualHostConfig with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ProxyVirtualHostConfig", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereHeaderAction":
        HeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderAction":
        HTTPRequestHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseHeaderAction":
        HTTPResponseHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereCompressionAction":
        CompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestCompressionAction":
        HTTPRequestCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseCompressionAction":
        HTTPResponseCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereCachingAction":
        CachingAction.create(objid, curjsonobject);
      elif currole == "WebSphereRewritingAction":
        RewritingAction.create(objid, curjsonobject);
      elif currole == "WebSphereRoutingAction":
        RoutingAction.create(objid, curjsonobject);

  # ProxyRuleExpression MUST be created after actions because it depends on their references
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProxyRuleExpression":
        ProxyRuleExpression.create(objid, curjsonobject);

  # ProxyVirtualHost MUST be created after ProxyRuleExpression because it depends on its references
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProxyVirtualHost":
        ProxyVirtualHost.create(objid, curjsonobject, "proxyVirtualHosts");

  # ProxyVirtualHostRef MUST be created after ProxyVirtualHost
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProxyVirtualHostRef":
        ProxyVirtualHostRef.doImport(objid, curjsonobject);
  Util.popPathElement('ProxyVirtualHostConfig');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  atts.append(['enabledProxyVirtualHosts','']);
  if len(atts) != 0:
    print "Modifying ProxyVirtualHostConfig with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  proxyActions = Util.parseConfigIdListAttribute(objid, 'proxyActions', "ProxyVirtualHostConfig");
  for proxyAction in proxyActions:
    if len(proxyAction) > 0:
      Util.remove(proxyAction);

  proxyRuleExpressions = Util.parseConfigIdListAttribute(objid, 'proxyRuleExpressions',"ProxyVirtualHostConfig");
  for proxyRuleExpression in proxyRuleExpressions:
    if len(proxyRuleExpression) > 0:
      Util.remove(proxyRuleExpression);

  enabledProxyVirtualHosts = Util.parseConfigIdListAttribute(objid, 'enabledProxyVirtualHosts',"ProxyVirtualHostConfig");
  for enabledProxyVirtualHost in enabledProxyVirtualHosts:
    if len(enabledProxyVirtualHost) > 0:
      Util.remove(enabledProxyVirtualHost);

  proxyVirtualHosts = Util.parseConfigIdListAttribute(objid, 'proxyVirtualHosts',"ProxyVirtualHostConfig");
  for proxyVirtualHost in proxyVirtualHosts:
    if len(proxyVirtualHost) > 0:
      Util.remove(proxyVirtualHost);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereHeaderAction":
        HeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderAction":
        HTTPRequestHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseHeaderAction":
        HTTPResponseHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereCompressionAction":
        CompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestCompressionAction":
        HTTPRequestCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseCompressionAction":
        HTTPResponseCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereCachingAction":
        CachingAction.create(objid, curjsonobject);
      elif currole == "WebSphereRewritingAction":
        RewritingAction.create(objid, curjsonobject);
      elif currole == "WebSphereRoutingAction":
        RoutingAction.create(objid, curjsonobject);

  # ProxyRuleExpression MUST be created after actions because it depends on their references
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProxyRuleExpression":
        ProxyRuleExpression.create(objid, curjsonobject);

  # ProxyVirtualHost MUST be created after ProxyRuleExpression because it depends on its references
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProxyVirtualHost":
        ProxyVirtualHost.create(objid, curjsonobject, "proxyVirtualHosts");

  # ProxyVirtualHostRef MUST be created after ProxyVirtualHost
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProxyVirtualHostRef":
        ProxyVirtualHostRef.doImport(objid, curjsonobject);
  Util.popPathElement('ProxyVirtualHostConfig');

def getProxyVirtualHostConfig(objid):
  proxyVirtualHostConfig = Util.getAssociatedObjects(objid, "ProxyVirtualHostConfig");
  if proxyVirtualHostConfig is not None and len(proxyVirtualHostConfig) > 0:
    return proxyVirtualHostConfig[0];
  return None;
