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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.rewritingactiontype", objid, "rewritingActionType","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.name", objid, "name","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.limiturlpattern", objid, "limitURLPattern","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.topattern", objid, "toPattern","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.limitcookiepath", objid, "limitCookiePath","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.enablepassiverewrite", objid, "enablePassiveRewrite","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.cookiename", objid, "cookieName","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.limitcookiedomain", objid, "limitCookieDomain","RewritingAction");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rewritingaction.frompattern", objid, "fromPattern","RewritingAction");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  headerAction = Util.getOptionalAttribute(objid, 'headerAction',"RewritingAction");
  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, HTTPRequestHeaderAction._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));

  httpCompressionAction = Util.getOptionalAttribute(objid, 'HTTPCompressionAction',"RewritingAction");
  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));

  routingAction = Util.getOptionalAttribute(objid, 'routingAction', 'RewritingAction');
  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));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "rewritingActionType", roleProperties.optString("websphere.rewritingaction.rewritingactiontype", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.rewritingaction.name", None));
  Util.addIfNotNone(properties, "limitURLPattern", roleProperties.optString("websphere.rewritingaction.limiturlpattern", None));
  Util.addIfNotNone(properties, "toPattern", roleProperties.optString("websphere.rewritingaction.topattern", None));
  Util.addIfNotNone(properties, "limitCookiePath", roleProperties.optString("websphere.rewritingaction.limitcookiepath", None));
  Util.addIfNotNone(properties, "enablePassiveRewrite", roleProperties.optString("websphere.rewritingaction.enablepassiverewrite", None));
  Util.addIfNotNone(properties, "cookieName", roleProperties.optString("websphere.rewritingaction.cookiename", None));
  Util.addIfNotNone(properties, "limitCookieDomain", roleProperties.optString("websphere.rewritingaction.limitcookiedomain", None));
  Util.addIfNotNone(properties, "fromPattern", roleProperties.optString("websphere.rewritingaction.frompattern", None));
  print "Creating RewritingAction with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("RewritingAction", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereHTTPRequestHeaderAction":
        HTTPRequestHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseHeaderAction":
        HTTPResponseHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestCompressionAction":
        HTTPRequestCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseCompressionAction":
        HTTPResponseCompressionAction.create(objid, curjsonobject);
      elif currole == "WebSphereRoutingAction":
        RoutingAction.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('RewritingAction');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.rewritingactiontype", None), "rewritingActionType","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.name", None), "name","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.limiturlpattern", None), "limitURLPattern","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.topattern", None), "toPattern","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.limitcookiepath", None), "limitCookiePath","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.enablepassiverewrite", None), "enablePassiveRewrite","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.cookiename", None), "cookieName","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.limitcookiedomain", None), "limitCookieDomain","RewritingAction");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rewritingaction.frompattern", None), "fromPattern","RewritingAction");
  if len(atts) != 0:
    print "Modifying RewritingAction with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

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

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

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