from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from AuthorizationGroupMember import AuthorizationGroupMember
from AuthorizationTableExt import AuthorizationTableExt

__name_att__ = "websphere.authorizationgroup.name"

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'AuthorizationGroup');

  containmentpath = "%(parentconpath)sAuthorizationGroup:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath);
  dict['conpath'] = containmentpath;
  return dict

def _export(objid, parentrespath, attName = None):
  Util.pushPathElement('AuthorizationGroup')

  ''' 
  There are two types of AuthorizationGroup:
    1)Cell ->  AuthorizationGroup
    2)AuthorizationGroup -> members -> AuthorizationGroup
  For 1), the attribute name is required, so attName must be None here, and name will get
    from Util.getRequiredAttribute(...)
  For 2), the attribute name is optional, that is, could be None, even be same within the same parent AuthorizationGroup.
    So attName is passed as name via line 82
    #82  Util.addAllFromExport(extraObjects, _export(member, currespath, "AuthorizationGroup%s" % groupi));            
  '''
  name = Util.getRequiredAttribute(objid, "name", 'AuthorizationGroup');
  if attName is not None:
    name = attName;


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.authorizationgroup.name", objid, "name","AuthorizationGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.authorizationgroup.resourcename", objid, "resourceName","AuthorizationGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.authorizationgroup.resourcetype", objid, "resourceType","AuthorizationGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.authorizationgroup.description", objid, "description","AuthorizationGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  
  hardcoded = 1;
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'memberProperties',"AuthorizationGroup","Member Properties", hardcoded);
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'groupProperties',"AuthorizationGroup","Group Properties", hardcoded);
  
  memberi = 0;
  groupi = 0;
  members = Util.parseConfigIdListAttribute(objid, 'members',"AuthorizationGroup");
  for member in members:
    if len(member) > 0:
      returndict = Util.createTypeFolder(respath, "AuthorizationGroupMember", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      if member.find("#AuthorizationGroupMember_") != -1:
        Util.addAllFromExport(extraObjects, AuthorizationGroupMember._export(member, currespath, "AuthorizationGroupMember%s" % memberi));
        memberi = memberi + 1;
      elif member.find("#AuthorizationGroup_") != -1:
        Util.addAllFromExport(extraObjects, _export(member, currespath, "AuthorizationGroup%s" % groupi));     
        groupi = groupi + 1;            

  i = 0;        
  authorizationTableExts = AuthorizationTableExt.getAuthorizationTableExts(objid);
  if authorizationTableExts is not None and len(authorizationTableExts) > 0:
    authorizationTableExtList = authorizationTableExts;
    for authorizationTableExt in authorizationTableExtList:
      if len(authorizationTableExt) > 0:
        returndict = Util.createTypeFolder(respath, "AuthorizationTableExt", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, AuthorizationTableExt._export(authorizationTableExt, currespath, "AuthorizationTableExt%s" % i));        
        i = i + 1;      
      
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('AuthorizationGroup');
  return result;



def doImport(containmentpath, roleName, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("AuthorizationGroup resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.authorizationgroup.name"):
    raise Exception("Resource role properties does not contain websphere.authorizationgroup.name!");

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    if parentid == None or len(parentid) == 0:
      raise Exception("Parent does not exist to create AuthorizationGroup on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.authorizationgroup.name"):
    raise Exception("Resource role properties does not contain websphere.authorizationgroup.name!");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.authorizationgroup.name", None));
  Util.addIfNotNone(properties, "resourceName", roleProperties.optString("websphere.authorizationgroup.resourcename", None));
  Util.addIfNotNone(properties, "resourceType", roleProperties.optString("websphere.authorizationgroup.resourcetype", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.authorizationgroup.description", None));
  print "Creating AuthorizationGroup with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("AuthorizationGroup", parentid, properties);
  
  Util.unsetAttribute(objid, 'members',"AuthorizationGroup");

  authorizationTableExts = AuthorizationTableExt.getAuthorizationTableExts(objid);
  if authorizationTableExts is not None and len(authorizationTableExts) > 0:
    authorizationTableExtList = authorizationTableExts;
    for authorizationTableExt in authorizationTableExtList:
      if len(authorizationTableExt) > 0:
        Util.remove(authorizationTableExt);            
      
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find("Member") > -1):
        attName = 'memberProperties';
      elif (foldername.find("Group") > -1):
        attName = 'groupProperties';
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole, attName);
      if propertyObject == 0:
        if currole == "WebSphereAuthorizationGroupMember":
          AuthorizationGroupMember.create(objid, curjsonobject);
        elif currole == "WebSphereAuthorizationGroup":
          create(objid, curjsonobject);          
        elif currole == "WebSphereAuthorizationTableExt":
          AuthorizationTableExt.create(objid, curjsonobject);          
  Util.popPathElement('AuthorizationGroup');
          
  return objid;


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.authorizationgroup.name"):
    raise Exception("Resource role properties does not contain websphere.authorizationgroup.name!");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.authorizationgroup.name", None), "name","AuthorizationGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.authorizationgroup.resourcename", None), "resourceName","AuthorizationGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.authorizationgroup.resourcetype", None), "resourceType","AuthorizationGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.authorizationgroup.description", None), "description","AuthorizationGroup");
  if len(atts) != 0:
    print "Modifying AuthorizationGroup with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'memberProperties',"AuthorizationGroup");
  Property.removeProperties(objid, 'groupProperties',"AuthorizationGroup");  

  Util.unsetAttribute(objid, 'members',"AuthorizationGroup");
      
  authorizationTableExts = AuthorizationTableExt.getAuthorizationTableExts(objid);
  if authorizationTableExts is not None and len(authorizationTableExts) > 0:
    authorizationTableExtList = authorizationTableExts;
    for authorizationTableExt in authorizationTableExtList:
      if len(authorizationTableExt) > 0:
        Util.remove(authorizationTableExt);              
      
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find("Member") > -1):
        attName = 'memberProperties';
      elif (foldername.find("Group") > -1):
        attName = 'groupProperties';
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole, attName);
      if propertyObject == 0:
        if currole == "WebSphereAuthorizationGroupMember":
          AuthorizationGroupMember.create(objid, curjsonobject);
        elif currole == "WebSphereAuthorizationGroup":
          create(objid, curjsonobject);                    
        elif currole == "WebSphereAuthorizationTableExt":
          AuthorizationTableExt.create(objid, curjsonobject);          
      
  Util.popPathElement('AuthorizationGroup');
