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

from django.http import Http404
from django.views.generic.dates import DateDetailView, ArchiveIndexView, \
    YearArchiveView, MonthArchiveView, DayArchiveView

from .models import NewsboxSEOBase, NewsboxExpiredBase


class NewsboxPublishedMixinView(object):

    def get_queryset(self):
        queryset = super(NewsboxPublishedMixinView, self).get_queryset()
        if not self.model.has_change_permission(self.request.user):
            queryset = queryset.filter(self.model.q_published())
        return queryset


class NewsboxBaseArchiveView(NewsboxPublishedMixinView):
    """
    This view is responsible for displaying a list of newsbox
    """
    date_field = "newsbox_publication_start_date"
    slug_field = "newsbox_slug"
    make_object_list = True
    allow_future = True
    title = None

    def get_context_data(self, *args, **kwargs):
        context = super(NewsboxBaseArchiveView, self).get_context_data(*args, **kwargs)
        if self.title is None:
            title = self.model._meta.verbose_name_plural.capitalize()
        else:
            title = self.title
        context.update({
            'model': self.model,
            'model_opts': self.model._meta,
            'instance': None,
            'title': title,
            'title_url': '',
            'newsbox_opts': self.model._newsbox_meta,
            'date_list_period': self.date_list_period,
        })
        if context['object_list']:
            context['current_date'] = context['object_list'][0].newsbox_publication_start_date
        return context


class NewsboxArchiveView(NewsboxBaseArchiveView, ArchiveIndexView):
    template_name_suffix = "_list"
    allow_empty = True


class NewsboxYearArchiveView(NewsboxBaseArchiveView, YearArchiveView):
    template_name_suffix = "_list"


class NewsboxMonthArchiveView(NewsboxBaseArchiveView, MonthArchiveView):
    template_name_suffix = "_list"
    month_format = "%m"


class NewsboxDayArchiveView(NewsboxBaseArchiveView, DayArchiveView):
    template_name_suffix = "_list"
    month_format = "%m"
    date_list_period = "day"


class NewsboxDetailView(NewsboxPublishedMixinView, DateDetailView):
    """
    This view is responsible for displaying a newsbox
    """
    month_format = "%m"
    date_field = "newsbox_publication_start_date"
    slug_field = "newsbox_slug"
    allow_future = True

    def get_context_data(self, **kwargs):
        context = super(NewsboxDetailView, self).get_context_data(**kwargs)
        if 'NewsboxCMSBase' in (base.__name__ for base in self.model.__bases__):
            from menus.utils import set_language_changer
            set_language_changer(self.request, self.object.get_absolute_url)
        context['newsbox_seo'] = isinstance(context['object'], NewsboxSEOBase)
        context['newsbox_expired'] = isinstance(context['object'], NewsboxExpiredBase)
        return context