from stronghold.decorators import public
from stronghold.views import StrongholdPublicMixin
from django.utils.decorators import method_decorator
from django.shortcuts import render
from django.views.generic import UpdateView, ListView
from django.http import HttpResponse, Http404
from django_filters.views import FilterView
from django_tables2 import SingleTableMixin, LazyPaginator
from django.urls import reverse_lazy
from .models import Players
from .tables import TeamTable, TeamHcapTable, TeamFilter, TeamScoresTable
from .forms import TeamForm
from django.contrib.auth.decorators import login_required
from .taranaki_pairs import main

# This is the team table
class TeamListView(StrongholdPublicMixin, SingleTableMixin, FilterView):
    model = Players
    table_class = TeamTable
    template_name = 'entries/team.html'
    filterset_class = TeamFilter

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)
    
# This is to edit a team   
class EditTeamView(UpdateView):
    model = Players
    form_class = TeamForm
    template_name =  'entries/edit.html'
    success_url = reverse_lazy('entries:teams-index')
    
    @method_decorator(public)
    def dispatch(self, *args, **kwargs):
       return super(EditTeamView, self).dispatch(*args, **kwargs)
    
# This is the team Handicap
class TeamHcapView(StrongholdPublicMixin, SingleTableMixin, ListView):
    model = Players
    table_class = TeamHcapTable
    template_name = 'entries/hcap.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)
   
# This is the team Handicap
class TeamScoresView(StrongholdPublicMixin, SingleTableMixin, ListView):
    model = Players
    table_class = TeamScoresTable
    template_name = 'entries/scores.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)   
    
def index(request):
    context = {'teams_count' : Players.objects.count(),
        'teams_unpaid' : Players.objects.filter(paid='NO').count(),
    }
    return render(request, 'entries/index.html', context)
	
def edit(request, team_id):
    try:
        team = Players.objects.get(pk=team_id)
    except Players.DoesNotExist:
        raise Http404("Team does not exist")
    return render(request, 'entries/edit.html', {'team': team, 'fields' : ('p1_name',)})

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)
    
def updateHandicaps(request):
    main(["reset"])
    return HttpResponse("Done")
    
def checkEmails(request):
    main([])
    return HttpResponse("Done")
    
def updateScores(request):
    return HttpResponse("Done")
