from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from GenericServerClusterRoute import GenericServerClusterRoute
from ApplicationServerRoute import ApplicationServerRoute
from FailRoute import FailRoute
from RedirectRoute import RedirectRoute
from LocalRoute import LocalRoute
from GenericClusterRoute import GenericClusterRoute
from CellRoute import CellRoute
from HTTPRequestHeaderAction import HTTPRequestHeaderAction
from HTTPResponseHeaderAction import HTTPResponseHeaderAction
from Property import Property

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.routingaction.name", objid, "name","RoutingAction");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"RoutingAction");

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

  routingAction = Util.getOptionalAttribute(objid, 'routingAction', 'RoutingAction');
  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, _export(routingAction, currespath, routingActionName));

  routeType = Util.getOptionalAttribute(objid, 'routeType',"RoutingAction");
  if routeType is not None and len(routeType) > 0:
    if routeType.find("#GenericServerClusterRoute_") != -1:
      returndict = Util.createTypeFolder(respath, "GenericServerClusterRoute", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, GenericServerClusterRoute._export(routeType, currespath, 'Generic Server Cluster Route'));
    elif routeType.find("#ApplicationServerRoute_") != -1:
      returndict = Util.createTypeFolder(respath, "ApplicationServerRoute", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ApplicationServerRoute._export(routeType, currespath, 'Application Server Route'));
    elif routeType.find("#FailRoute_") != -1:
      returndict = Util.createTypeFolder(respath, "FailRoute", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, FailRoute._export(routeType, currespath, 'Fail Route'));
    elif routeType.find("#RedirectRoute_") != -1:
      returndict = Util.createTypeFolder(respath, "RedirectRoute", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, RedirectRoute._export(routeType, currespath, 'Redirect Route'));
    elif routeType.find("#LocalRoute_") != -1:
      returndict = Util.createTypeFolder(respath, "LocalRoute", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, LocalRoute._export(routeType, currespath, 'Local Route'));
    elif routeType.find("#GenericClusterRoute_") != -1:
      returndict = Util.createTypeFolder(respath, "GenericClusterRoute", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, GenericClusterRoute._export(routeType, currespath, 'Generic Cluster Route'));
    elif routeType.find("#CellRoute_") != -1:
      returndict = Util.createTypeFolder(respath, "CellRoute", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, GenericClusterRoute._export(routeType, currespath, 'Cell Route'));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereGenericServerClusterRoute":
        GenericServerClusterRoute.create(objid, curjsonobject);
      elif currole == "WebSphereApplicationServerRoute":
        ApplicationServerRoute.create(objid, curjsonobject);
      elif currole == "WebSphereFailRoute":
        FailRoute.create(objid, curjsonobject);
      elif currole == "WebSphereRedirectRoute":
        RedirectRoute.create(objid, curjsonobject);
      elif currole == "WebSphereLocalRoute":
        LocalRoute.create(objid, curjsonobject);
      elif currole == "WebSphereGenericClusterRoute":
        GenericClusterRoute.create(objid, curjsonobject);
      elif currole == "WebSphereCellRoute":
        CellRoute.create(objid, curjsonobject);
      elif currole == "WebSphereRoutingAction":
        create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderAction":
        HTTPRequestHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseHeaderAction":
        HTTPResponseHeaderAction.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('RoutingAction');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

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

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereGenericServerClusterRoute":
        GenericServerClusterRoute.create(objid, curjsonobject);
      elif currole == "WebSphereApplicationServerRoute":
        ApplicationServerRoute.create(objid, curjsonobject);
      elif currole == "WebSphereFailRoute":
        FailRoute.create(objid, curjsonobject);
      elif currole == "WebSphereRedirectRoute":
        RedirectRoute.create(objid, curjsonobject);
      elif currole == "WebSphereLocalRoute":
        LocalRoute.create(objid, curjsonobject);
      elif currole == "WebSphereGenericClusterRoute":
        GenericClusterRoute.create(objid, curjsonobject);
      elif currole == "WebSphereCellRoute":
        CellRoute.create(objid, curjsonobject);
      elif currole == "WebSphereRoutingAction":
        create(objid, curjsonobject);
      elif currole == "WebSphereHTTPRequestHeaderAction":
        HTTPRequestHeaderAction.create(objid, curjsonobject);
      elif currole == "WebSphereHTTPResponseHeaderAction":
        HTTPResponseHeaderAction.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('RoutingAction');
