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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jaasconfigurationentry.alias", objid, "alias","JAASConfigurationEntry");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  #We need to determine the "ordernum" for the login module. 
  #this is based on when the login modules were created relative to one another.
  #unfortunately, the only way websphere identifies this is through the config id which is of the form filelocation#ObjectType_TimeStamp
  #thanks websphere
  loginModMap = {};
  jaasLoginModules = Util.parseConfigIdListAttribute(objid, 'loginModules',"JAASConfigurationEntry");
  for jaasLoginModule in jaasLoginModules:
    if len(jaasLoginModule) > 0:
      loginModMap[Util.getTimeStampFromObjectId(jaasLoginModule)] = jaasLoginModule;

  sortedJaasLoginModules = [];
  keys = loginModMap.keys();
  keys.sort();
  for x in keys:
    sortedJaasLoginModules.append(loginModMap[x]);

  i = 0;
  for jaasLoginModule in sortedJaasLoginModules:
    if len(jaasLoginModule) > 0:
      jaasLoginModule = jaasLoginModule[jaasLoginModule.find("("):len(jaasLoginModule)];
      returndict = Util.createTypeFolder(respath, "JAASLoginModule", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, JAASLoginModule._export(jaasLoginModule, currespath, "JAAS Login Module%s" % i, i));
      i = i + 1;

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


def doImport(containmentpath, roleName, jsonobject):
  Log.debug("Determining if JAASConfigurationEntry already exists for this partial apply...");
  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.jaasconfigurationentry.alias"):
    raise Exception("Resource role properties does not contain websphere.jaasconfigurationentry.alias!");

  resourceName = roleProperties.optString("websphere.jaasconfigurationentry.alias");

  # Security object has two attributes of type JAASConfiguration:
  # applicationLoginConfig and systemLoginConfig.
  # We need to get the right JAASConfiguration since it is a parent of JAASConfigurationEntry
  # To do that, we will check the jsonobject's path.
  # Paths for applicationLoginConfig contain "Application Login Config":
  #  "/@websphere.cell@/Securities/Security/Application Login Config/JAASConfiguration/JAAS Configuration Entries/name"
  # Paths for systemLoginConfig contain "System Login Config":
  #  "/@websphere.cell@/Securities/Security/System Login Config/JAASConfiguration/JAAS Configuration Entries/name"
  path = jsonobject.getString("path");
  Log.debug("JSON path of JAASConfigurationEntry object to search on is " + str(path));
  typeOfJAASConfiguration = "";
  applicationLoginConfigIndex = path.find("/Security/Application Login Config/");
  systemLoginConfigIndex = path.find("/Security/System Login Config/");
  if applicationLoginConfigIndex != -1:
    typeOfJAASConfiguration = "application";
  if systemLoginConfigIndex != -1:
    typeOfJAASConfiguration = "system";
  if typeOfJAASConfiguration == "":
    raise Exception("While performing a partial update of JAASConfigurationEntries, could not find their parent JAASConfiguration. Containment path was " + str(containmentpath));
  Log.debug("Type of JAASConfiguration object this JAASConfigurationEntry belongs to is is " + str(typeOfJAASConfiguration));

  # We can now run AdminTask.listJAASLoginEntries to get the entries for the correct JAASConfiguration
  foundJAASConfigurationEntry = findJAASConfigurationEntry(typeOfJAASConfiguration, resourceName)

  if Util.__removePartialConfig__ == "true":
    if foundJAASConfigurationEntry != "":
      Util.removePartialApply(foundJAASConfigurationEntry);
      foundJAASConfigurationEntry = None;
    else:
      Log.debug("While running remove partial config, could not find object of type JAASConfigurationEntry with containment path " + str(containmentpath));
  else:
    if foundJAASConfigurationEntry == "":
      # we can't get the parent JAASConfiguration object id,
      # so we need to create the JAASConfigurationEntry with an AdminTask command
      params = "[-loginEntryAlias " + resourceName + " -loginType " + typeOfJAASConfiguration + "]";
      Log.debug("About to run AdminTask.configureJAASLoginEntry with params " + str(params));
      Util.configureJAASLoginEntry(params);
      # unfortunately, it doesn't return the objid of the created JAASConfigurationEntry.
      # so, we need to find it
      foundJAASConfigurationEntry = findJAASConfigurationEntry(typeOfJAASConfiguration, resourceName);
      Log.debug("Created JAASConfigurationEntry " + str(foundJAASConfigurationEntry));
      # finally, let's do an update to make sure we update the children properties...
    # update regardless of if we just created it or found an existing JAASConfigurationEntry
    update(foundJAASConfigurationEntry,jsonobject);
  return foundJAASConfigurationEntry;

def doImportPartial(containmentpath, roleName, jsonobject):
  return doImport(containmentpath, roleName, jsonobject);

def findJAASConfigurationEntry(typeOfJAASConfiguration, resourceName):
  foundJAASConfigurationEntry = "";
  params = "[-loginType " + typeOfJAASConfiguration + "]";
  entries = Util.listJAASLoginEntries(params).splitlines();
  for entry in entries:
    jaasLabelIndex = entry.find("#JAASConfigurationEntry");
    if jaasLabelIndex != -1:
      jaasStartIndex = entry.rfind(" ", 0, jaasLabelIndex) + 1;
      jaasEndIndex = entry.find("]", jaasLabelIndex);
      jaasObjIncompleteId = entry[jaasStartIndex:jaasEndIndex];
      jaasObjId = "(" + str(jaasObjIncompleteId) + ")"
      # now that we have the config id of a JAASConfigurationEntry,
      # see if its alias matches the alias in the config json
      alias = Util.getRequiredAttribute(jaasObjId, "alias", "JAASConfigurationEntry");
      if alias == resourceName:
        foundJAASConfigurationEntry = jaasObjId;
        break;
  return foundJAASConfigurationEntry;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  jaasLoginModules = Util.parseConfigIdListAttribute(objid, 'loginModules',"JAASConfigurationEntry");
  for jaasLoginModule in jaasLoginModules:
    if len(jaasLoginModule) > 0:
      Util.remove(jaasLoginModule);

  jaasLoginModulesForCreation = {};
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereJAASLoginModule":
        ordernum = JAASLoginModule.getOrderFromJSON(curjsonobject);
        if ordernum is not None:
          jaasLoginModulesForCreation[long(ordernum)] = curjsonobject;
        else:
          JAASLoginModule.create(objid, curjsonobject);
    jaaskeys = jaasLoginModulesForCreation.keys();
    jaaskeys.sort();
    for x in jaaskeys:
      JAASLoginModule.create(objid, jaasLoginModulesForCreation[x]);
  Util.popPathElement('JAASConfigurationEntry');


def getAliasFromJSON(jsonobject):
  roleProperties = jsonobject.getJSONObject("roleProperties");
  return roleProperties.optString("websphere.jaasconfigurationentry.alias", None);
