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

__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 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);
