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

__name_att__ = None;

def _export(objid, parentrespath, name = "JAAS Configuration"):
  Util.pushPathElement('JAASConfiguration')

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

  roleProperties = JSONObject();

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  jaasConfigurationEntries = Util.parseConfigIdListAttribute(objid, 'entries',"JAASConfiguration");
  for jaasConfigurationEntry in jaasConfigurationEntries:
    if len(jaasConfigurationEntry) > 0:
      returndict = Util.createTypeFolder(respath, "JAASConfigurationEntry", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      jaasConfigurationEntryAlias = Util.getOptionalAttribute(jaasConfigurationEntry, "alias", "JAASConfigurationEntry");
      if jaasConfigurationEntryAlias == None or len(jaasConfigurationEntryAlias) == 0:
        jaasConfigurationEntryAlias = ("JAAS Configuration Entry%s" % i)
      Util.addAllFromExport(extraObjects, JAASConfigurationEntry._export(jaasConfigurationEntry, currespath, jaasConfigurationEntryAlias));
      i = i + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  print "Creating JAASConfiguration with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("JAASConfiguration", parentid, properties, attName);

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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  if len(atts) != 0:
    print "Modifying JAASConfiguration with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  jaasConfigurationEntryMap = getJAASConfigurationEntryMap(objid);
  entriesToCreate = [];
  aliasesUpdated = [];

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereJAASConfigurationEntry":
        alias = JAASConfigurationEntry.getAliasFromJSON(curjsonobject);
        if jaasConfigurationEntryMap.has_key(alias):
          JAASConfigurationEntry.update(jaasConfigurationEntryMap[alias], curjsonobject);
          aliasesUpdated.append(alias);
        else:
          entriesToCreate.append(curjsonobject);
    for curjsonobject in entriesToCreate:
      JAASConfigurationEntry.create(objid, curjsonobject)
    for alias in jaasConfigurationEntryMap.keys():
      if not alias in aliasesUpdated:
        Util.remove(jaasConfigurationEntryMap[alias]);

  Util.popPathElement('JAASConfiguration');


def getJAASConfigurationEntryMap(jaasConfId):
  result = {};
  jaasConfigurationEntries = Util.parseConfigIdListAttribute(jaasConfId, 'entries',"JAASConfiguration");
  for x in jaasConfigurationEntries:
    alias = Util.getRequiredAttribute(x, 'alias', 'JAASConfigurationEntry');
    if alias is not None:
      result[alias] = x;

  return result;
