from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
import AdminTask;  # @UnresolvedImport
from EndPoint import EndPoint
from OverlayEndpoint import OverlayEndpoint
from SSLConfigGroup import SSLConfigGroup
from utilities import Util
from WASConfLog import Log;

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namedendpoint.endpointname", objid, "endPointName","NamedEndPoint");
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  # by default, NamedEndPoints inherit SSL configuration (from a node or cell).
  # if the inherited SSL configuration has been overridden, there is an SSLConfigGroup
  #  object for the NamedEndPoint
  scope = scope + ":(endpoint):%s" % name
  sslConfigGroups = getNamedEndPointSSLConfigGroups(name, scope);
  i = 0;
  for sslConfigGroup in sslConfigGroups:
    returndict = Util.createTypeFolder(respath, "SSLConfigGroup", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    sslCGName = Util.getRequiredAttribute(sslConfigGroup, "name", "SSLConfigGroup")
    if i == 0:
      Util.addAllFromExport(extraObjects, SSLConfigGroup._export(sslConfigGroup, currespath, sslCGName));
    else:
      # print warning because while we may manually add more than one SSLConfigGroup to an end point,
      #   you can't do so through admin console and I doubt having more than one SSLConfigGroup is valid
      Log.logMsg("More than one SSLConfigGroup was found for " + str(objid), Log.LogLevelWarn);
      Util.addAllFromExport(extraObjects, SSLConfigGroup._export(sslConfigGroup, currespath, sslCGName + i));
    i = i + 1;

  exportedObject.put("roleProperties", roleProperties);

  endpoint = Util.getOptionalAttribute(objid, 'endPoint',"NamedEndPoint");
  if len(endpoint) > 0:
    if endpoint.find("#EndPoint_") != -1:
      returndict = Util.createTypeFolder(respath, "EndPoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, EndPoint._export(endpoint, currespath, "EndPoint"));
    elif endpoint.find("#OverlayEndpoint_") != -1:
      returndict = Util.createTypeFolder(respath, "OverlayEndpoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, OverlayEndpoint._export(endpoint, currespath, "OverlayEndpoint"));

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        EndPoint.create(objid, curjsonobject, 'endPoint');
      elif currole == "WebSphereOverlayEndpoint":
        OverlayEndpoint.create(objid, curjsonobject, 'endPoint');
      elif currole == "WebSphereSSLConfigGroup":
        securityObjId = Util.getSecurityObjId();
        SSLConfigGroup.create(securityObjId, curjsonobject);
  Util.popPathElement('NamedEndPoint');


def deleteNamedEndPointSSLConfigGroups(name, scope):
  sslConfigGroups = getNamedEndPointSSLConfigGroups(name, scope);
  for sslConfigGroup in sslConfigGroups:
    Util.remove(sslConfigGroup, 1);

def getNamedEndPointSSLConfigGroups(name, scope):
  # get all SSLConfigGroups belonging to a NamedEndPoint with our NamedEndPoint's name
  sslConfigGroups = Util.getid("/SSLConfigGroup:%s/" % name);
  sslConfigGroups = Util.parseConfigIdList(sslConfigGroups);
  foundObjects = [];
  # go through the SSLConfigGroups and see if their scope matches the scope of our
  # NamedEndPoint. To get the scope, get the SSLConfigGroup's ManagementScope object's
  # scopeName attribute.
  for sslConfigGroup in sslConfigGroups:
    if len(sslConfigGroup) > 0:
      ms = Util.getRequiredAttribute(sslConfigGroup, "managementScope", "SSLConfigGroup")
      foundScope = Util.getRequiredAttribute(ms, "scopeName", "ManagementScope")
      if foundScope == scope:
        foundObjects.append(sslConfigGroup);
  return foundObjects;

