from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from allocation.models import * 
#from allocation.forms import PreferenceForm
from django.forms import modelform_factory
from django.forms import modelformset_factory
from django.views import generic
from django.views.generic.edit import *

from allocation.models import Choice
from allocation.models import Applicant
from django.shortcuts import render, redirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.contrib.auth import authenticate, login
from django import forms
import csv
from django.urls import reverse_lazy

from alloc import *

# @login_required(login_url='/admin/login')
# def index(request): #for /allocation
#   applicant=Applicant.objects.filter(name=request.user.username)[0]
#   # form = PreferenceForm(
#   #   initial={'name': applicant.name , 'rank': applicant.rank}
#   #   )
#   form = ArticleForm(instance=applicant)
#   return render(request, 'allocation/index.html', {'applicant': applicant, 'form': form})

def button_action(request):
    # value = request.POST["prikey"]
    # value = int(value.split('/')[-3])
    # name = Institute.objects.get(pk=value).name
    # allocator(name)
    # return HttpResponse("success")
    institute=request.user.username
    allocator(institute)
    return HttpResponse("success")

def home(request):
    documents = Document.objects.all()
    return render(request, 'core/home.html', { 'documents': documents })
    return HttpResponse("On home")

def choice_make(request):
    if request.method == "POST":
        csvfile = request.FILES['myfile']
        file_data = csvfile.read().decode("utf-8")
        lines = file_data.split("\n")
        user_name = request.user.username
        institute = Institute.objects.filter(name=user_name)[0]
        for line in lines:
            line =  line.split(',')
            # tmp = Choice.objects.create(choice_name=line[0],capacity=line[1])
            tmp = institute.choices.create(choice_name=line[0],capacity=line[1])
            tmp.save()
        return HttpResponse("successful")
    return HttpResponse("Error")


def applicant_make(request):
    if request.method == "POST":
        csvfile = request.FILES['myfile']
        file_data = csvfile.read().decode("utf-8")
        user_name = request.user.username
        institute = Institute.objects.filter(name=user_name)[0]
        lines = file_data.split("\n")
        for line in lines:
            line = line.split(',')
            # tmp = Applicant.objects.create(name = line[0],rank=line[1])
            tmp = institute.applicants.create(name = line[0],rank = line[1])
            tmp.save()
            user = User.objects.create_user(username=line[2],email=line[3],password=line[4])
            user.is_staff = True
            user.save()
        return HttpResponse("successful")
    return HttpResponse("Error")


AppFormset = modelformset_factory(Application,fields=("choice", "priority" ), extra=5)

@login_required(login_url='/admin/login')
def index(request): #for /allocation
    applicant=Applicant.objects.filter(name=request.user.username)[0]
    # form1 = modelform_factory(Applicant, fields=("name", "rank" ))
    formset = AppFormset(queryset=Application.objects.filter(applicant=applicant),)
    return render(request, 'allocation/index.html', {'applicant': applicant,  'formset': formset,})


# def submit(request):
#   if request.method == 'POST':
#       formset = AppFormset(request.POST)
#       if formset.is_valid():
#           for form in formset:
#               if form.is_valid():
#                   cd = f.cleaned_data
#                   application.applicant=cd.get('applicant')
#                   application.choice=cd.get('choice')
#                   application.priority=cd.get('priority')
#                   application.save()
#       else:
#           return HttpResponse('error')


def submit(request):
    if request.method == 'POST':
        formset = AppFormset(request.POST)
        instances = formset.save()
        return HttpResponse("successful")

@login_required(login_url='/admin/login')
def admin1(request):
    institute=Institute.objects.filter(name=request.user.username)[0]
    return render(request, 'allocation/admin1.html',{'institute': institute})


class ChoiceListView(generic.ListView):
    model = Choice
    def get_context_data(self, **kwargs):
        institute=Institute.objects.filter(name=self.request.user.username)[0]
        context = super(ChoiceListView, self).get_context_data(**kwargs)
        context['institute'] = institute
        return context
    def get_queryset(self):
        institute=Institute.objects.filter(name=self.request.user.username)[0]
        return Choice.objects.filter(institute__name=institute.name)

class ApplicantListView(generic.ListView):
    model = Applicant
    def get_context_data(self, **kwargs):
        institute=Institute.objects.filter(name=self.request.user.username)[0]
        context = super(ApplicantListView, self).get_context_data(**kwargs)
        context['institute'] = institute
        return context
    def get_queryset(self):
        institute=Institute.objects.filter(name=self.request.user.username)[0]
        return Applicant.objects.filter(institute__name=institute.name)

class ChoiceDetailView(generic.DetailView):
    model = Choice
    def get_context_data(self, **kwargs):
        institute=Institute.objects.filter(name=self.request.user.username)[0]
        context = super(ChoiceDetailView, self).get_context_data(**kwargs)
        context['institute'] = institute
        return context

class ApplicantDetailView(generic.DetailView):
    model = Applicant
    def get_context_data(self, **kwargs):
        institute=Institute.objects.filter(name=self.request.user.username)[0]
        context = super(ApplicantDetailView, self).get_context_data(**kwargs)
        context['institute'] = institute
        return context

class ChoiceCreateView(CreateView):
    model = Choice
    fields = ['choice_name', 'capacity', 'institute']

class ChoiceUpdate(UpdateView):
    model = Choice
    fields = ['choice_name','capacity']
    template_name_suffix = '_update'
    success_url = 'allocation:choice_list'

class ChoiceDelete(DeleteView):
    model = Choice
    success_url = reverse_lazy('allocation:choice_list')



