# -*- coding: utf-8 -*-
from django.shortcuts import redirect
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic import UpdateView, ListView, DetailView

from portal.forms import ProfileEditForm
from portal.models import DownloadFile, Announcement, Information


class ContentQuerysetMixin(object):
    def get_queryset(self):
        queryset = self.model.objects.all()
        if not self.request.user.is_superuser:
            queryset = queryset.filter(groups__in=self.request.user.groups.all())
            queryset = queryset.filter(published=True)
        return queryset


class OverviewView(ContentQuerysetMixin, ListView):
    template_name = 'portal/overview.html'
    open_tasks = None
    paginate_by = 5
    model = Announcement

    def get_information_sections(self):
        informations = Information.objects.filter(section__isnull=False, groups__in=self.request.user.groups.all())
        sections = {}
        for information in informations:
            if not sections.get(information.section_id, None):
                sections[information.section_id] = {
                    'section': information.section,
                    'items': []
                }
            sections[information.section_id]['items'].append(information)

        sections_list = [{'title': x['section'].title, 'items': x['items'], 'ordering': x['section'].ordering} for x in
                         sections.values()]

        return sorted(sections_list, key=lambda x: x['ordering'])

    def get_download_sections(self):
        file_list = DownloadFile.objects.filter(groups__in=self.request.user.groups.all())
        sections = {}
        for file in file_list:
            if not sections.get(file.section_id, None):
                sections[file.section_id] = {
                    'section': file.section,
                    'items': []
                }
            sections[file.section_id]['items'].append(file)

        sections_list = [{'title': x['section'].title, 'items': x['items'], 'ordering': x['section'].ordering} for x in
                         sections.values()]

        return sorted(sections_list, key=lambda x: x['ordering'])

    def get_queryset(self):
        queryset = super(OverviewView, self).get_queryset()
        return queryset.filter(informed_users__in=[self.request.user])

    def get_open_tasks(self):
        queryset = ContentQuerysetMixin.get_queryset(self).exclude(informed_users__in=[self.request.user])
        return queryset

    def get_settings(self):
        settings = (
            (_('Benutzerdaten'), reverse_lazy('portal:edit_profile')),
            (_('Passwort'), reverse_lazy('portal:change_password')),
        )
        return settings

    def get_context_data(self, **kwargs):
        context = super(OverviewView, self).get_context_data(**kwargs)
        context.update({
            'information_sections': self.get_information_sections(),
            'download_sections': self.get_download_sections(),
            'settings': self.get_settings()
        })
        self.open_tasks = self.get_open_tasks()
        if not self.request.GET.get(self.page_kwarg, None) and self.open_tasks.count() > 0:
            context.update({
                'object_list': self.open_tasks,
                'open_object_list': True
            })
        return context


class AnnouncementDetailView(ContentQuerysetMixin, DetailView):
    template_name = 'portal/content.html'
    model = Announcement

    def post(self, request, *args, **kwargs):
        self.get_object().informed_users.add(self.request.user)
        return redirect('portal:overview')


class InformationDetailView(ContentQuerysetMixin, DetailView):
    template_name = 'portal/content.html'
    model = Information


class ProfileEditView(UpdateView):
    form_class = ProfileEditForm
    template_name = 'portal/edit_form.html'
    success_url = reverse_lazy('portal:edit_profile_success')

    def get_object(self, queryset=None):
        return self.request.user.profile
