# -*- encoding: utf-8 -*-
from django.contrib.auth import login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator
from django.http import HttpRequest
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView, View
from django.views.generic.base import TemplateView
from elasticsearch.exceptions import ConnectionError

from scriptorium.base import ScriptoriumAssetsMixIn
from scriptorium.elasticsearch.scriptorium import LatestUpdatedPackagesPicker
from scriptorium.views import GuestRequiredMixIn
from .models import SignupForm, LoginForm, User, SearchForm


class PackageProfileView(ScriptoriumAssetsMixIn, TemplateView):
    template_name = "frontpage/package/view.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        owner = User.objects.get(username=kwargs.get('username'))
        package = owner.package_set.get(name=kwargs.get('package_name'))
        script_paginator = Paginator(package.script_set.all(), 10)

        context['script_paginator'] = script_paginator
        context['script_page'] = script_paginator.page(
            self.request.GET.get('page', 1))

        context['owner'] = owner
        context['package'] = package

        return context


class HomepageView(ScriptoriumAssetsMixIn, TemplateView):
    template_name = "frontpage/homepage.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        form = SearchForm(self.request.GET)
        context['search_results'] = form.get_results()

        try:
            context['latest_updates'] = LatestUpdatedPackagesPicker().search()
        except ConnectionError:
            context['latest_updates'] = []
        return context


class LoginView(ScriptoriumAssetsMixIn, GuestRequiredMixIn, FormView):
    template_name = "frontpage/login.html"
    form_class = LoginForm

    def get_initial(self):
        self.success_url = self.request.GET.get('next', None) or reverse(
            'user_dashboard')
        return super().get_initial()

    def form_valid(self, form: LoginForm):
        """
        Get the user instance and login to with the current request-session.
        :param form:
        """

        try:
            user = form.get_instance()  # type: User
        except ObjectDoesNotExist:
            form.add_error('email', _('email not found'))
        else:
            if user.check_password(form.data.get('password')):
                login(self.request, user)
            else:
                form.add_error('password', _('wrong password!'))

        if len(form.errors) > 0:
            return self.render_to_response(self.get_context_data(form=form))
        else:
            return super(LoginView, self).form_valid(form)


class SignupView(ScriptoriumAssetsMixIn, GuestRequiredMixIn, FormView):
    template_name = "frontpage/signup.html"
    form_class = SignupForm

    def form_valid(self, form: SignupForm):
        user = form.instance  # type: User
        user.set_password(user.password)
        user.save()

        return redirect('login')


class LogoutView(ScriptoriumAssetsMixIn, LoginRequiredMixin, View):
    url = "homepage"

    def get(self, request: HttpRequest, *args, **kwargs):
        logout(request)
        return redirect(self.url)
