# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.conf import settings
from django.contrib import messages
from django.core import urlresolvers
from django.utils.decorators import method_decorator
from django.utils.translation import gettext_lazy as _
from django.views import generic as views
from django_yauth.decorators import yalogin_required

from app import forms
from app.decorators import email_required_redirect, yalogin_required_redirect
from app.views import mixins
from core.misc import captcha
from core.models import NewPaymentInfo


__all__ = ['PaymentInfoView']


class PaymentInfoView(mixins.MenuMixin,
                      mixins.PasswordRefreshMixin,
                      views.UpdateView):
    form_class = forms.NewPaymentInfoForm
    template_name = 'payment_edit.html'
    success_url = urlresolvers.reverse_lazy('payment-info')

    def get_initial(self):
        is_russian_resident = self.request.LANGUAGE_CODE == 'ru'
        bank_type = '0'  # не выбрано
        if self.object is not None:
            # is_russian_resident – или тип "резидент РФ", или если пока ещё ничего не известно
            is_russian_resident = self.object.datasync_values.get('type') in (NewPaymentInfo.RESIDENT_TYPE, None)
            bank_type = self.object.datasync_values.get('bank-type', '0')
        return {
            'is_russian_resident': is_russian_resident,
            'bank_type': bank_type,
        }

    def get_object(self, queryset=None):
        return getattr(self.request.user, 'new_payment_info', None)

    def get_context_data(self, **kwargs):
        context_data = super(PaymentInfoView, self).get_context_data(captcha=captcha.Captcha(), **kwargs)
        return context_data

    def form_valid(self, form):
        instance = form.instance
        instance.reporter = self.request.user
        result = super(PaymentInfoView, self).form_valid(form)
        messages.success(self.request, _('payment_info.success'))
        return result

    def form_invalid(self, form):
        if 'captcha' in form.errors:
            messages.error(self.request, _('captcha.is_not_valid'))
        else:
            messages.error(self.request, _('payment_info.invalid_form'))
        return super(PaymentInfoView, self).form_invalid(form)

    def post(self, request, *args, **kwargs):
        return super(PaymentInfoView, self).post(request, *args, **kwargs)

    @method_decorator(yalogin_required_redirect(redirect_url=settings.LOGIN_URL))
    @method_decorator(email_required_redirect(redirect_url='email-required'))
    def dispatch(self, request, *args, **kwargs):
        return super(PaymentInfoView, self).dispatch(request, *args, **kwargs)
