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

__name_att__ = "websphere.proxyruleexpressionref.name"

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

  if name == "":
    name = Util.getRequiredAttribute(objid, "name", "ProxyRuleExpression");
  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 WebSphereProxyRuleExpressionRef");
  exportedObject.put("roleName", "WebSphereProxyRuleExpressionRef");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.proxyruleexpressionref.name", objid, "name","ProxyRuleExpression");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ProxyRuleExpressionRef');
  return result;


def doImport(parentid, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("WebSphereProxyRuleExpressionRef resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.proxyruleexpressionref.name"):
    raise Exception("Resource role properties does not contain websphere.proxyruleexpressionref.name!");

  proxyRuleExpressionName = roleProperties.optString("websphere.proxyruleexpressionref.name", None);
  serverName = parentid.split('/servers/')[1].split('|')[0];
  if serverName == None or len(serverName) == 0:
    clusterName = parentid.split('/clusters/')[1].split('|')[0];
    containmentPath = "/ServerCluster:" + clusterName + "/ProxyVirtualHostConfig:/ProxyRuleExpression:" + proxyRuleExpressionName + "/";
  else:
    containmentPath = "/Server:" + serverName + "/ProxyVirtualHostConfig:/ProxyRuleExpression:" + proxyRuleExpressionName + "/";
  proxyRuleExpression = Util.getid(containmentPath);
  if proxyRuleExpression == None or len(proxyRuleExpression) == 0:
      raise Exception("Could not determine the Proxy Rule Expression for ProxyRuleExpressionRef " + proxyRuleExpressionName + ". Searched on containment path " + containmentPath + ".");

  Util.pushPathElement("Server");
  Util.pushPathElement("ProxyVirtualHostConfig");
  Util.modify(parentid, [['enabledProxyRuleExpressions', proxyRuleExpression]]);
  Util.popPathElement("ProxyVirtualHostConfig");
  Util.popPathElement("Server");

