from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
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 utilities import Util
from Property import Property

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.routingrule.virtualhostname", objid, "virtualHostName","RoutingRule");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.routingrule.urigroup", objid, "uriGroup","RoutingRule");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.routingrule.name", objid, "name","RoutingRule");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.routingrule.isenabled", objid, "isEnabled","RoutingRule");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"RoutingRule");

  routingAction = Util.getRequiredAttribute(objid, 'routingAction',"RoutingRule");
  if routingAction is not None and len(routingAction) > 0:

    if routingAction.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(routingAction, currespath, 'Generic Server Cluster Route'));
    elif routingAction.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(routingAction, currespath, 'Application Server Route'));
    elif routingAction.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(routingAction, currespath, 'Fail Route'));
    elif routingAction.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(routingAction, currespath, 'Redirect Route'));
    elif routingAction.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(routingAction, currespath, 'Local Route'));
    elif routingAction.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(routingAction, currespath, 'Generic Cluster Route'));
    elif routingAction.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(routingAction, currespath, 'Cell Route'));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "virtualHostName", roleProperties.optString("websphere.routingrule.virtualhostname", None));
  Util.addIfNotNone(properties, "uriGroup", roleProperties.optString("websphere.routingrule.urigroup", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.routingrule.name", None));
  Util.addIfNotNone(properties, "isEnabled", roleProperties.optString("websphere.routingrule.isenabled", None));
  print "Creating RoutingRule with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("RoutingRule", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if jsonobject.has('children'):
        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);
        else:
          propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('RoutingRule');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.routingrule.virtualhostname", None), "virtualHostName","RoutingRule");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.routingrule.urigroup", None), "uriGroup","RoutingRule");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.routingrule.name", None), "name","RoutingRule");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.routingrule.isenabled", None), "isEnabled","RoutingRule");
  if len(atts) != 0:
    print "Modifying RoutingRule with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  routingAction = Util.getRequiredAttribute(objid, 'routingAction',"RoutingRule");
  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 == "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);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('RoutingRule');
