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

import logging

from django import http
from django.conf import settings
from django.shortcuts import render
from django_yauth import util as yauth_utils

from core import models


logger = logging.getLogger(__name__)


class EditablePageMixin(object):

    def _get_page(self):
        try:
            page = self.object
        except AttributeError:
            slug = self.kwargs.get('slug', self.page_slug)
            page = models.PageTranslation.published.get(page__slug=slug)
        return page

    def get_context_data(self, **kwargs):
        page = self._get_page()
        language_code = self.request.LANGUAGE_CODE
        title = getattr(page, 'title_%s' % language_code)
        html = getattr(page, 'html_%s' % language_code)
        return super(EditablePageMixin, self).get_context_data(
            title=title,
            html=html,
            **kwargs
        )



class MenuMixin(object):

    def get_context_data(self, **kwargs):
        menu_items = models.PageTranslation.published.filter(page__order__gt=0).values_list(
            'page__slug', 'title_%s' % self.request.LANGUAGE_CODE)
        return super(MenuMixin, self).get_context_data(
            menu_items=menu_items,
            **kwargs
        )


class PasswordRefreshMixin(object):

    def dispatch(self, request, *args, **kwargs):
        password_verification_age = request.yauser.blackbox_result['password_verification_age']
        logger.debug('Password verification age: %s', password_verification_age)
        if password_verification_age > settings.MAX_PASSWORD_VERIFICATION_AGE:
            verify_url = yauth_utils.get_passport_url('verify', request=request, retpath=True)         
            context = {'render_context': 'open_redirect', 'url': verify_url.replace('pay', 'payment-settings')}
            return render(request, 'redirect.html', context)
        return super(PasswordRefreshMixin, self).dispatch(request, *args, **kwargs)
