# Create your views here.

import django_comments as comments
import os
from django.conf import settings
from django.http import HttpResponse, Http404
from django.utils.translation import ugettext as _
from django.views import generic

from . import models, forms
from aggregator.models import Feed
from events.models import Photo
from utils.mixins import PermissionRequiredMixin


class ArticleArchiveMixin(object):
    def get_category(self, queryset):
        try:
            self.category = models.Category.objects.get(slug=self.kwargs['category'])
            return queryset.filter(category=self.category)
        except models.Category.DoesNotExist:
            raise Http404(_("This Category does not exist."))
        except KeyError:
            self.category = None
            return self.queryset

    def get_context_data(self, **kwargs):
        context = super(ArticleArchiveMixin, self).get_context_data(**kwargs)
        context['categories'] = models.Category.objects.all()
        context['active_category'] = self.category
        context['feeds'] = Feed.objects.active()
        return context


class ArticleArchiveIndex(ArticleArchiveMixin, generic.ArchiveIndexView):
    queryset = models.Article.objects.filter(status=models.STATUS_PUBLISHED)
    date_field = 'date_created'
    paginate_by = 5
    context_object_name = 'article_list'
    allow_empty = True

    def get_queryset(self):
        queryset = generic.ArchiveIndexView.get_queryset(self)
        queryset = self.get_category(queryset)
        return queryset


class ArticleYearArchive(ArticleArchiveMixin, generic.YearArchiveView):
    queryset = models.Article.objects.filter(status=models.STATUS_PUBLISHED)
    date_field = 'date_created'
    paginate_by = 5
    year_format = '%Y'
    make_object_list = True
    allow_empty = True

    def get_queryset(self):
        queryset = generic.YearArchiveView.get_queryset(self)
        queryset = self.get_category(queryset)
        return queryset


class ArticleMonthArchive(ArticleArchiveMixin, generic.MonthArchiveView):
    queryset = models.Article.objects.filter(status=models.STATUS_PUBLISHED)
    date_field = 'date_created'
    month_format = '%m'
    paginate_by = 5
    make_object_list = True
    allow_empty = True

    def get_queryset(self):
        queryset = generic.MonthArchiveView.get_queryset(self)
        queryset = self.get_category(queryset)
        return queryset


class ArticleDetail(generic.DetailView):
    queryset = models.Article.objects.filter(status=models.STATUS_PUBLISHED)


class ArticleForm(PermissionRequiredMixin, generic.UpdateView):
    model = models.Article
    form_class = forms.ArticleForm
    permission_required = 'content.change_article'

    def get_context_data(self, **kwargs):
        context = super(ArticleForm, self).get_context_data(**kwargs)
        if self.kwargs.get('pk'):
            context['title'] = _("Edit Article")
        else:
            context['title'] = _("Create Article")
        return context

    def get_object(self, **kwargs):
        if self.kwargs.get('pk', None):
            return models.Article.objects.get(pk=self.kwargs['pk'])
        else:
            return models.Article(author=self.request.user)


class ImageList(generic.View):
    # noinspection PyMethodMayBeStatic
    def get(self, kwargs):
        image_list = []
        response = HttpResponse(content_type='text/javascript')
        response.write('var tinyMCEImageList = new Array(')
        os.chdir(settings.MEDIA_ROOT)
        for dirpath, dirnames, filenames in os.walk(
                'images'):  # @UnusedVariable @IgnorePep8
            filenames.sort()
            for filename in filenames:
                image_list.append('["%(name)s", "%(path)s"]' % {
                    'name': os.path.join(dirpath, filename),
                    'path': os.path.join(settings.MEDIA_URL, dirpath, filename)
                })
        response.write(', '.join(image_list))
        response.write(');')
        return response


class PageAddForm(PermissionRequiredMixin, generic.CreateView):
    form_class = forms.PageForm
    template_name = 'content/page_form.html'
    permission_required = 'content.add_page'

    def get_initial(self):
        path = os.path.splitext(self.kwargs['path'])[0]
        if path.startswith('/'):
            path = path[1:]
        if path.endswith('/'):
            path = path[:-1]
        parent = models.Page.objects.get(path=path)
        return {'parent': parent}


class PageEditForm(PermissionRequiredMixin, generic.UpdateView):
    form_class = forms.PageForm
    permission_required = 'content.change_page'

    def get_object(self, queryset=None):
        path = os.path.splitext(self.kwargs['path'])[0]
        if path.startswith('/'):
            path = path[1:]
        if path.endswith('/'):
            path = path[:-1]
        return models.Page.objects.get(path=path)


class PageHtml(generic.DetailView):
    def get_object(self, queryset=None):
        try:
            return models.Page.objects.get(path=self.kwargs['path'],
                                           content_type=1)
        except models.Page.DoesNotExist:
            raise Http404(
                _("No Page found matching the Path %s") % self.request.path
            )

    def get_template_names(self):
        return self.object.template


class PagePdf(generic.DeleteView):
    def get_object(self, queryset=None):
        try:
            return models.Page.objects.get(path=self.kwargs['path'],
                                           content_type=2)
        except models.Page.DoesNotExist:
            raise Http404(
                _("No PDF Document found matching the Path %s") %
                self.request.path
            )

    def render_to_response(self, context, **response_kwargs):
        try:
            pdf_file = open(self.object.pdf_file.path, 'rb')
            response = HttpResponse(pdf_file.read(),
                                    content_type='application/pdf')
            pdf_file.close()
            return response
        except:
            raise Http404('File not Found %s.pdf' % self.kwargs['path'])


class PageList(generic.View):
    # noinspection PyMethodMayBeStatic
    def get(self, kwargs):
        response = HttpResponse(content_type='text/javascript')
        response.write('var tinyMCELinkList = new Array(')
        page_list = []
        for page in models.Page.objects.filter(status=models.STATUS_PUBLISHED):
            page_list.append('["%(name)s", "%(path)s"]' % {
                'name': page.menu_name,
                'path': page.get_absolute_url()
            })
        response.write(', '.join(page_list))
        response.write(');')
        return response


class StartPage(generic.TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        page = models.Page.objects.get(slug='index')
        random_photo = Photo.objects.get_random(startpage=True)
        recent_comment_list = comments.get_model().objects.filter(
            site__pk=settings.SITE_ID,
            is_public=True,
            is_removed=False,
        )
        recent_comment_list = recent_comment_list.order_by('-submit_date')[:10]
        context = {
            'title': page.title,
            'content': page.content,
            'random_photo': random_photo.callout,
            'recent_article_list': models.Article.objects.published()[:3],
            'recent_comment_list': recent_comment_list,
        }
        return context

    queryset = models.Article.objects.filter(status=models.STATUS_PUBLISHED)
