from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from ErrorMapping import ErrorMapping

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.localerrorpagepolicy.handlelocalerrors", objid, "handleLocalErrors","LocalErrorPagePolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.localerrorpagepolicy.handleremoteerrors", objid, "handleRemoteErrors","LocalErrorPagePolicy");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  errorMappings = Util.parseConfigIdListAttribute(objid, 'errorMappings',"LocalErrorPagePolicy");
  for errorMapping in errorMappings:
    if len(errorMapping) > 0:
      returndict = Util.createTypeFolder(respath, "ErrorMapping", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ErrorMapping._export(errorMapping, currespath, "Error Mapping%s" % i));
      i = i + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereErrorMapping":
        ErrorMapping.create(objid, curjsonobject)
  Util.popPathElement('LocalErrorPagePolicy');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  errorMappings = Util.parseConfigIdListAttribute(objid, 'errorMappings',"LocalErrorPagePolicy");
  for errorMapping in errorMappings:
    if len(errorMapping) > 0:
      Util.remove(errorMapping);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereErrorMapping":
        ErrorMapping.create(objid, curjsonobject)

  Util.popPathElement('LocalErrorPagePolicy');
