# -*- coding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from django.core.exceptions import ValidationError
from django.shortcuts import redirect, render
from django.utils.translation import ugettext_lazy as _
from django.views import generic

from account.forms import SignInForm, SignUpForm


class SignInFormView(generic.FormView):
    """
    Represents the 'Sign In' view.
    """
    form_class = SignInForm
    success_url = '/'
    template_name = 'clintya_site/account/signin.html'

    def form_valid(self, form):
        """
        Authenticates and login the user only if it is active.
        """
        email = form.cleaned_data['email']
        password = form.cleaned_data['password']

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

        if user is not None:
            if user.is_active:
                login(self.request, user)

                return super(SignInFormView, self).form_valid(form)
            else:
                form.add_error(
                    'email',
                    ValidationError(_("Your account has been disabled."))
                )
        else:
            form.add_error(
                'email',
                ValidationError(_("The email or password is invalid."))
            )

        return render(self.request, self.template_name, context={'form': form})


class SignUpFormView(generic.FormView):
    """
    Represents the 'Sign Up' view.
    """
    form_class = SignUpForm
    success_url = '/'
    template_name = 'clintya_site/account/signup.html'

    def form_valid(self, form):
        """
        Registers the new user, logout the current user, authenticates,
        and login the new user.
        """
        email = form.cleaned_data['email']
        password = form.cleaned_data['password']

        form.save()

        logout(self.request)

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

        if user is not None and user.is_active:
            login(self.request, user)

        return super(SignUpFormView, self).form_valid(form)


def signout_view(request):
    """
    Represents the 'Sign Out' view to logout the authenticated user.
    """
    logout(request)

    return redirect('/')
