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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.authorizationtableext.context", objid, "context","AuthorizationTableExt");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.authorizationtableext.filename", objid, "fileName","AuthorizationTableExt");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  
  typeFolders = {};
  
  i = 0;
  authorizations = Util.parseConfigIdListAttribute(objid, 'authorizations',"AuthorizationTableExt");
  for authorization in authorizations:
    if len(authorization) > 0:
      returndict = Util.createTypeFolder(respath, "RoleAssignmentExt", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, RoleAssignmentExt._export(authorization, currespath, "RoleAssignmentExt%s" % i));
      i = i + 1;    
  
  i = 0;
  roles = Util.parseConfigIdListAttribute(objid, 'roles',"AuthorizationTableExt");
  for role in roles:
    if len(role) > 0:
      returndict = Util.createTypeFolder(respath, "SecurityRoleExt", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SecurityRoleExt._export(role, currespath, "SecurityRoleExt%s" % i));
      i = i + 1;    
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('AuthorizationTableExt');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "context", roleProperties.optString("websphere.authorizationtableext.context", None));
  Util.addIfNotNone(properties, "fileName", roleProperties.optString("websphere.authorizationtableext.filename", None));

  # The roles added as a property during create
  # So, we are doing things a little out of order here.
  roles = [];
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      curroleProperties = curjsonobject.getJSONObject("roleProperties");
      specificRole = [];
      if currole == "WebSphereSecurityRoleExt":
        Util.addIfNotNone(specificRole, "roleName", curroleProperties.optString("websphere.securityroleext.rolename", None), "SecurityRoleExt");
        Util.addIfNotNone(specificRole, "description", curroleProperties.optString("websphere.securityroleext.description", None), "SecurityRoleExt");
        roles.append(Util._genStringFromProperties(specificRole));

  if len(roles) > 0:
    Util.addIfNotNone(properties, "roles", roles);

  print "Creating AuthorizationTableExt with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("AuthorizationTableExt", parentid, properties);
  
  authorizations = Util.parseConfigIdListAttribute(objid, 'authorizations',"AuthorizationTableExt");
  for authorization in authorizations:
    if len(authorization) > 0:
      Util.remove(authorization);    
    
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereRoleAssignmentExt":
        RoleAssignmentExt.create(objid, curjsonobject);      
  Util.popPathElement('AuthorizationTableExt');


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  authorizations = Util.parseConfigIdListAttribute(objid, 'authorizations',"AuthorizationTableExt");
  for authorization in authorizations:
    if len(authorization) > 0:
      Util.remove(authorization);    

  # It is not possible to update roles on a AuthorizationTableExt object because it is a read-only attribute.
  # I think that is okay because we always delete and recreate AuthorizationTableExt objects and their children anyway.
  #roles = Util.parseConfigIdListAttribute(objid, 'roles',"AuthorizationTableExt");
  #for role in roles:
  #  if len(role) > 0:
  #    Util.remove(role);
      
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereRoleAssignmentExt":
        RoleAssignmentExt.create(objid, curjsonobject);
      # It is not possible to update roles on a AuthorizationTableExt object because it is a read-only attribute.
      #elif currole == "WebSphereSecurityRoleExt":
      #  SecurityRoleExt.create(objid, curjsonobject);
  Util.popPathElement('AuthorizationTableExt');
        
    
def getAuthorizationTableExts(objid):
  authorizationTableExts = Util.getAssociatedObjects(objid, "AuthorizationTableExt");
  return authorizationTableExts;    

