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

from app.views import mixins
from django.utils.dates import MONTHS
from django.views.generic import ListView

from core.models import HallOfFameGroup
from core.models import Reporter
from core.utils import external_userinfo_by_uid, BlackboxUserError

__all__ = ['HallOfFameAll', 'HallOfFameMonth']


class HallOfFameBase(mixins.MenuMixin, mixins.EditablePageMixin, ListView):
    paginate_by = 27
    page_slug = 'hall_of_fame'
    template_name = 'hall_of_fame.html'

    def get_context_data(self, **kwargs):
        return super(HallOfFameBase, self).get_context_data(
            reporters=self.get_username_list(),
            month=self.get_current_month(),
            year=self.get_current_year(),
            months=MONTHS.items(),
            years=self.get_published_years(),
            **kwargs)

    def get_username_list(self):
        object_list_uid_values = self.object_list.values('uid')
        uids = [item['uid'] for item in object_list_uid_values]
        for uid in uids:
            try:
                reporter = external_userinfo_by_uid(uid)
            except BlackboxUserError:
                #  TODO: user not found in BB
                pass
            else:
                # TODO(remedy) Do not skip empty usernames
                if reporter.username:
                    yield reporter

    def get_current_month(self):
        return HallOfFameGroup.published.last_month()

    def get_current_year(self):
        return HallOfFameGroup.published.last_year()

    def get_published_years(self):
        return HallOfFameGroup.published.years()


class HallOfFameAll(HallOfFameBase):

    def get_queryset(self):
        return Reporter.objects.filter(
            show_on_hall=True,
            hall_of_fame_groups__is_published=True).distinct().order_by('?')

    def get_context_data(self, **kwargs):
        context = super(HallOfFameAll, self).get_context_data(**kwargs)
        context['all_time'] = True
        return context


class HallOfFameMonth(HallOfFameBase):

    def get_queryset(self):
        self.current_month = self.kwargs.get(
            'month', HallOfFameGroup.published.last_month())
        self.current_year = self.kwargs.get(
            'year', HallOfFameGroup.published.last_year())
        return Reporter.objects.filter(
            show_on_hall=True,
            hall_of_fame_groups__is_published=True,
            hall_of_fame_groups__month=self.current_month,
            hall_of_fame_groups__year=self.current_year).order_by('?')

    def get_current_month(self):
        return int(self.current_month)

    def get_current_year(self):
        return int(self.current_year)
