from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SpecialSubjectExt import SpecialSubjectExt
from GroupExt import GroupExt
from UserExt import UserExt
from SecurityRoleExtRef import SecurityRoleExtRef

__name_att__ = None;

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


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

  roleProperties = JSONObject();

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

  typeFolders = {};
  
  extraObjects = SpecialSubjectExt.exportSpecialSubjectExts(objid, respath, extraObjects, typeFolders, 'specialSubjects',"RoleAssignmentExt","SpecialSubjectExt");

  i = 0;
  groups = Util.parseConfigIdListAttribute(objid, 'groups',"RoleAssignmentExt");
  for group in groups:
    if len(group) > 0:
      returndict = Util.createTypeFolder(respath, "GroupExt", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, GroupExt._export(group, currespath, "GroupExt%s" % i));
      i = i + 1;      
  
  i = 0;
  users = Util.parseConfigIdListAttribute(objid, 'users',"RoleAssignmentExt");
  for user in users:
    if len(user) > 0:
      returndict = Util.createTypeFolder(respath, "UserExt", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, UserExt._export(user, currespath, "UserExt%s" % i));
      i = i + 1;      

  role = Util.getRequiredAttribute(objid, 'role', 'RoleAssignmentExt');
  if role is not None and len(role) > 0:
    returndict = Util.createTypeFolder(respath, "SecurityRoleExtRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, SecurityRoleExtRef._export(role, currespath, 'Security Role Ext'));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  groups = Util.parseConfigIdListAttribute(objid, 'groups',"RoleAssignmentExt");
  for group in groups:
    if len(group) > 0:
      Util.remove(group);    

  users = Util.parseConfigIdListAttribute(objid, 'users',"RoleAssignmentExt");
  for user in users:
    if len(user) > 0:
      Util.remove(user);

  Util.unsetAttribute(objid, 'role',"RoleAssignmentExt");
      
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      specialSubjectExtObject = SpecialSubjectExt.createObjIfRole(objid, curjsonobject, currole, "specialSubjects");  
      if specialSubjectExtObject == 0:
        if currole == "WebSphereGroupExt":
          GroupExt.create(objid, curjsonobject);      
        elif currole == "WebSphereUserExt":
          UserExt.create(objid, curjsonobject);
        elif currole == "WebSphereSecurityRoleExtRef":
          SecurityRoleExtRef.create(objid, curjsonobject, "role", "RoleAssignmentExt");
  Util.popPathElement('RoleAssignmentExt');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

    Util.modify(objid, atts);
  else:   
    print "RoleAssignmentExt configuration up to date.";
    
  SpecialSubjectExt.removeSpecialSubjectExts(objid, 'specialSubjects',"RoleAssignmentExt");    

  groups = Util.parseConfigIdListAttribute(objid, 'groups',"RoleAssignmentExt");
  for group in groups:
    if len(group) > 0:
      Util.remove(group);    

  users = Util.parseConfigIdListAttribute(objid, 'users',"RoleAssignmentExt");
  for user in users:
    if len(user) > 0:
      Util.remove(user);  
  
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      specialSubjectExtObject = SpecialSubjectExt.createObjIfRole(objid, curjsonobject, currole, "specialSubjects");  
      if specialSubjectExtObject == 0:
        if currole == "WebSphereGroupExt":
          GroupExt.create(objid, curjsonobject);      
        elif currole == "WebSphereUserExt":
          UserExt.create(objid, curjsonobject);
        elif currole == "WebSphereSecurityRoleExtRef":
          SecurityRoleExtRef.create(objid, curjsonobject, "role", "RoleAssignmentExt");
  Util.popPathElement('RoleAssignmentExt');
