import djconfig
from django.contrib.auth.views import LoginView as BaseLoginView
from django.http import Http404
from django.views.generic import TemplateView, FormView

from cabinet.utils import CabinetViewMixin


class CabinetIndexView(CabinetViewMixin, TemplateView):
    template_name = 'cabinet/index.html'
    title = 'Cabinet home'


class LoginView(BaseLoginView):
    template_name = 'cabinet/login.html'
    redirect_authenticated_user = True

    def get_context_data(self, **kwargs):
        ctx = super(LoginView, self).get_context_data(**kwargs)
        ctx['title'] = 'Login'
        return ctx

    def form_valid(self, form):
        res = super(LoginView, self).form_valid(form)
        if not self.request.POST.get('remember'):
            self.request.session.set_expiry(0)
        return res


class AdminConfigView(CabinetViewMixin, FormView):
    template_name = 'cabinet/admin_config.html'

    def get_sidebar_section(self):
        return 'admin_{}'.format(self.get_form_class().slug)

    def get_success_url(self):
        return ''

    def get_title(self):
        return '{} config'.format(self.get_form_class().title)

    def get_form_class(self):
        for form in djconfig.config._registry:
            if form.slug == self.kwargs.get('slug'):
                return form
        raise Http404()

    def form_valid(self, form):
        form.save()
        return super(AdminConfigView, self).form_valid(form)
