from django.shortcuts import redirect
from django.http import Http404
from django.views.generic.edit import FormView, UpdateView, DeleteView
from django.views.generic import ListView
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse, reverse_lazy

from .models import Adress

from .loginform import LoginForm
from .registerform import RegisterForm
from .adressform import AdressForm


class Login(FormView):
    template_name = 'form.html'
    form_class = LoginForm
    success_url = reverse_lazy('shop:index')

    def form_valid(self, form):
        user = form.getuser()

        if user is not None and user.is_active:
            login(self.request, user)
            return super().form_valid(form)
        else:
            raise Http404

def logoutView(request):
    logout(request)
    return redirect(reverse_lazy('shop:index'))


class Register(FormView):
    template_name = 'form.html'
    form_class = RegisterForm
    success_url = reverse_lazy('shop:index')

    def form_valid(self, form):
        user = form.save(commit=False)
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user.set_password(password)
        user.save()

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

        if user is not None and user.is_active:
            login(self.request, user)
            return super().form_valid(form)
        else:
            raise Http404

class AddAdress(FormView):
    template_name = 'form.html'
    form_class = AdressForm
    success_url = reverse_lazy('info:adresslist')

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.save()
        return super().form_valid(form)

class AdressList(ListView):
    template_name = 'info/adresslist.html'
    model = Adress

    def get_queryset(self):
        return self.model.objects.filter(user__username=self.request.user.username)

class DeleteAdress(DeleteView):
        template_name = 'form.html'
        success_url = reverse_lazy('info:adresslist')
        model = Adress

        def get(self, request, **kwargs):
            return self.post(request)

class EditAdress(UpdateView):
    template_name = 'form.html'
    form_class = AdressForm
    success_url = reverse_lazy('info:adresslist')
    model = Adress

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.save()
        return super().form_valid(form)
