from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from presiding.models import Post, UserProfile, CandidateProfile, CandidatePost, Voter, Vote
from django.contrib import messages
import datetime
from django.views.decorators.cache import cache_control
from django.http import HttpResponseRedirect
from django.db.models import Count


def su_login(request):
    page="su_login"

    if request.user.is_authenticated:
        return redirect('create_post')

    if request.method == 'POST':
        username = request.POST.get('username').lower().replace(" ", "").strip()
        password = request.POST.get('password')

        try:
            user = User.objects.get(username=username)
        except:
            messages.error(request, 'User does not exist')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            if request.user.userprofile.is_superuser == True:
                messages.success(request, 'Logged in as '+user.username) 
                return redirect('create_post')
            else:
                logout(request)
                messages.error(request, 'You are not authorized')
                return redirect('su_login')
        else:
            messages.error(request, 'Username OR password does not exit')


    context = {'page': page}
    return render(request, 'su/login.html', context)


@login_required(login_url='su_login')
def create_post(request):
    page="create_post"
    post_data = Post.objects.all()

    if request.method == 'POST':
        Post.objects.create(
            post_name = request.POST.get('post_name').upper().strip(),
        )
        messages.success(request, 'Post added: '+request.POST.get('post_name').upper().replace(" ", "").strip())

    context = {'page': page, 'post_data': post_data}
    return render(request, 'su/create-post.html', context)


@login_required(login_url='su_login')
def update_post(request, pk):
    page="update_post"
    post_data = Post.objects.all()
    post_single_data = Post.objects.get(id=pk)

    if request.method == 'POST':
        post_single_data.post_name =  request.POST.get('post_name').upper().strip()
        post_single_data.save()
        messages.success(request, 'Post updated : '+post_single_data.post_name)
        return redirect('create_post')

    context = {'page': page, 'post_data': post_data, 'post_single_data': post_single_data}
    return render(request, 'su/create-post.html', context)



@login_required(login_url='su_login')
def delete_post(request, pk):
    page="delete_post"
    post_data = Post.objects.all()
    post_single_data = Post.objects.get(id=pk)

    if request.method == 'POST':
        post_single_data.delete()
        messages.success(request, 'Post deleted : '+post_single_data.post_name)
        return redirect('create_post')


    context = {'page': page, 'post_data': post_data, 'post_single_data': post_single_data}
    return render(request, 'su/create-post.html', context)


@login_required(login_url='su_login')
def upload_candidates(request):
    page="upload_candidates"
    post_data = Post.objects.all()
    candidate_post_data = CandidatePost.objects.all()

    if request.method == 'POST':
        candidate_profile_save = CandidateProfile.objects.create(
            candidate_full_name = request.POST.get('candidate_full_name').upper().strip(),
            candidate_photo = request.FILES.get('candidate_photo'),
            election_year = datetime.date.today().year,
        )
        for data in request.POST.get('candidate_post').upper().strip():
            candidate_post_save = CandidatePost.objects.create(
                candidate_profile = candidate_profile_save,
            )
            candidate_post_save.post.set(request.POST.getlist('candidate_post'))
        messages.success(request, 'Candidate added: '+request.POST.get('candidate_full_name').upper().replace(" ", "").strip())

    context = {'page': page, 'post_data': post_data, 'candidate_post_data': candidate_post_data}
    return render(request, 'su/upload.html', context)



@login_required(login_url='su_login')
def update_candidates(request, pk):
    page="update_candidates"
    post_data = Post.objects.all()
    candidate_post_data = CandidatePost.objects.all()
    candidate_post_single_data = CandidatePost.objects.get(id=pk)
    candidate_post_single_relation_data = candidate_post_single_data.post.values_list('post_name', flat = True)
    
    if request.method == 'POST':
        candidate_post_single_data.candidate_full_name = request.POST.get('candidate_full_name').upper().strip()
        candidate_post_single_data.candidate_photo = request.FILES.get('candidate_photo')
        candidate_post_single_data.election_year = datetime.date.today().year

    context = {'page': page, 'post_data': post_data, 'candidate_post_data': candidate_post_data, 'candidate_post_single_data': candidate_post_single_data, 'candidate_post_single_relation_data': candidate_post_single_relation_data}
    return render(request, 'su/upload.html', context)



@login_required(login_url='su_login')
def delete_candidates(request, pk):
    page="delete_candidates"
    post_data = Post.objects.all()
    candidate_post_data = CandidatePost.objects.all()
    candidate_post_single_data = CandidatePost.objects.get(id=pk)
    candidate_post_single_relation_data = candidate_post_single_data.post.values_list('post_name', flat = True)

    if request.method == 'POST':
        candidate_post_single_data.delete()
        messages.success(request, 'Candidate deleted : '+candidate_post_single_data.candidate_profile.candidate_full_name)
        return redirect('upload_candidates')


    context = {'page': page, 'post_data': post_data, 'candidate_post_data': candidate_post_data, 'candidate_post_single_data': candidate_post_single_data, 'candidate_post_single_relation_data': candidate_post_single_relation_data}
    return render(request, 'su/upload.html', context)


@login_required(login_url='su_login')
def election_result(request):
    page="election_result"
    post_data = Post.objects.all()
    candidate_post_data = CandidatePost.objects.all()
    vote_data = Vote.objects.all()
    
    candidate_count = CandidateProfile.objects.all()
    voter_count = UserProfile.objects.filter(voter_vote_flag=True)
    vote_count = Vote.objects.all()
    post_count = Post.objects.all()
    
    result_data = Vote.objects.values('candidate_post_id').annotate(Count('id')).order_by().filter(id__count__gt=0)
    candidate_count_filter = CandidatePost.objects.values('post').annotate(Count('id')).order_by().filter(id__count__gt=0) 


    context = {'page': page, 'post_data': post_data, 'candidate_post_data': candidate_post_data, 'vote_data': vote_data, 'result_data': result_data, 'candidate_count': candidate_count, 'voter_count': voter_count, 'vote_count': vote_count, 'post_count': post_count, 'candidate_count_filter': candidate_count_filter}
    return render(request, 'su/results.html', context)


@cache_control(no_cache=True, must_revalidate=True, no_store=True)
@login_required(login_url='su_login')
def su_logout(request):
    logout(request)
    messages.error(request, 'You are logged out')
    return HttpResponseRedirect('su')



