from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from models import Project,ProjectAllocation,ProjectMetadata,Egroups
from forms import ProjectForm
from django.db import transaction
from getPrivileges import isSuperUser
from ldapSearch import checkEGroup
from django.db.models import Q
from commonFunctions import *
from validator import *
#import copy
import simplejson

def checkNameIgnoreCase(projectName):
    projectExists = False
    if Project.objects.filter(name__iexact=projectName).exists():
        projectExists = True
    return projectExists

def isAdminOfAnyProject(adminGroups):
    userIsAdmin = False
    if len(adminGroups) < 1:
       return userIsAdmin
    qset = Q(admin_group__exact=adminGroups[0])
    if len(adminGroups) > 1:
       for group in adminGroups[1:]:
         qset = qset | Q(admin_group__exact=group)
    if (Project.objects.filter(qset)).exists():
        userIsAdmin = True
    return userIsAdmin

def isAdminOfProject(adminGroups, projectName):
    userIsAdmin = False
    if len(adminGroups) < 1:
        return userIsAdmin
    try:
        prObject = Project.objects.get(name=projectName)
        prGroup = prObject.admin_group
        if prGroup in adminGroups:
            userIsAdmin = True
        else:
            userIsAdmin = False
    except Project.DoesNotExist:
        userIsAdmin = False
    return userIsAdmin

def isUserAllowedToUpdateOrDeleteProject(projectName,groupsList):
    userIsSuperUser = isSuperUser(groupsList)
    if userIsSuperUser:
        return True
    else:
        userIsAdmin = isAdminOfProject(groupsList,projectName)
        return userIsAdmin

@transaction.commit_on_success
def addnew(request):
    groups = request.META.get('ADFS_GROUP','')
    groupsList = groups.split(';') ;
    ## add operation is allowed only if user has cloudman resource manager privileges
    userIsSuperUser = isSuperUser(groupsList)
    if not userIsSuperUser:
        message = "You don't have cloudman resource manager privileges. Hence you are not authorized to add new Projects";
        html = "<html><body> %s.</body></html>" % message
        return HttpResponse(html)

    ## if the request if due to form submission, then add the project or else return to display the form for add
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        attr_name_array = request.POST.getlist('attribute_name');
        attr_value_array = request.POST.getlist('attribute_value');
        #Create dictionary of attr_name and attr_value with attr_name:attr_value as key:value pairs
        attr_list = createDictFromList(attr_name_array,attr_value_array)
        ## validate the form
        if form.is_valid():
            redirectURL = '/cloudman/message/?msg=' 
            name = form.cleaned_data['name']
            projectExists = checkNameIgnoreCase(name)
            if projectExists:
                msgAlreadyExists = 'Project ' + name + ' already exists. Hence Add Project Operation Stopped'
                return HttpResponseRedirect(redirectURL + msgAlreadyExists);
            description = form.cleaned_data['description']
            admin_group = form.cleaned_data['admin_group']
            comment = form.cleaned_data['comment']
            try:
                validate_attr(attr_list)
            except ValidationError as e:
                msg = 'Add Project Form  '+', '.join(e.messages)
                html = "<html><HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"4; url=/cloudman/project/list/\"></HEAD><body> %s.</body></html>" %msg
                return HttpResponse(html)
            ## check first whether the admin_group exists in the local egroup table
            ## if not, then in the remote egroup database through ldap. If exists here, then add to the local table
            egroup = None
            try:
                egroup = Egroups.objects.get(name=admin_group)
            except Egroups.DoesNotExist:
                if not (checkEGroup(admin_group)):
                    errorMessage = 'Admin E-Group Entered ' + admin_group + ' does not exists'
                    return HttpResponseRedirect(redirectURL + errorMessage)
                egroup = Egroups(name=admin_group)
                egroup.save()
            #Make Sure no attribute_name or attribute_value is empty
            ##Check if all the attribute name are distinct for this first convert all the attribute name to uppercase and 
            ## After converting to uppercase check for duplicate in the array
            if checkForEmptyStrInList(attr_name_array):
                errorMessage = 'Attribute Name Cannot be Empty. Hence Add Project Operation Stopped'
                return HttpResponseRedirect(redirectURL + errorMessage)
            ##Check if all the attribute name are distinct for this first convert all the attribute name to uppercase and 
            ## After converting to uppercase check for duplicate in the array
            new_attr_name_array = [x.upper() for x in attr_name_array];
            if len(new_attr_name_array) != len( set(new_attr_name_array) ):
                errorMessage = 'Duplicate values for the Attribute Name. Hence Add Project Operation Stopped#'
                return HttpResponseRedirect(redirectURL + errorMessage)
            ## add the project and return a success message to the user
            ##Also add the project_metadata
            try:
                projectObj = Project(name=name, description=description, admin_group=admin_group)			
                projectObj.save()
                proj=Project.objects.get(name=name)
                for attr_name,attr_value  in attr_list.items():
                    project_metadata = ProjectMetadata(attribute = attr_name,value = attr_value,project = proj)
                    project_metadata.save()
                    #Write the LOg               
                projectObj = Project.objects.get(name=name)
                if addLog(request,name,comment,projectObj,None,'project','add',True):
                    transaction.commit()          
                    msgSuccess = 'New Project ' +name  + ' added successfully'
                else:
                    transaction.rollback()
                    msgSuccess = 'Error in creating the Project ' + name
            except Exception:
                print traceback.format_exc()
                transaction.rollback()
                msgSuccess = 'Error in creating the Project ' + name

            html = "<html><HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"4; url=/cloudman/project/list/\"></HEAD><body> %s.</body></html>" % msgSuccess
            return HttpResponse(html)
    else:
        form = ProjectForm()
    return render_to_response('project/addnew.html',locals(),context_instance=RequestContext(request))


def listall(request):
    groups = request.META.get('ADFS_GROUP','')
    groupsList = groups.split(';') ;
    userIsSuperUser = isSuperUser(groupsList)
    projectsList = Project.objects.all().order_by('name')
    deleteDict = {}