from __future__ import absolute_import, unicode_literals

from collections import OrderedDict

from django.urls import reverse, reverse_lazy
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

from arctic.generics import (
    CreateView,
    DeleteView,
    ListView,
    TemplateView,
    UpdateView,
)
from arctic.generics import collapsible_gettext as _c

from .forms import AdvancedArticleSearchForm, ArticleForm, FiltersAndSearchForm
from .inlines import ImagesInline
from .models import Article, Category, Tag


class DashboardView(TemplateView):
    template_name = "arctic/index.html"
    page_title = "Dashboard"
    permission_required = "view_dashboard"

    def get_context_data(self, **kwargs):
        context = super(DashboardView, self).get_context_data(**kwargs)
        return context


class ArticleListView(ListView):
    paginate_by = 10
    model = Article
    fields = ["title", "description", "published", "category", "tags"]
    ordering_fields = ["title", "description", "category", "published"]
    search_fields = ["title"]
    simple_search_form_class = FiltersAndSearchForm
    advanced_search_form_class = AdvancedArticleSearchForm
    breadcrumbs = (("Home", "index"), ("Article List", None))
    action_links = [
        ("detail", "articles:detail", "fa-edit"),
        ("delete", "articles:delete", "fa-trash"),
    ]
    field_links = {
        "title": "articles:detail",
        "category": ("articles:category-detail", "category_id"),
    }
    tool_links_collapse = 2
    tool_links = [
        (_("Create Article"), "articles:create", "fa-plus"),
        (_("Export CSV"), ("get_export_url", "csv"), "fa-download"),
    ]
    field_classes = {"published": ""}

    permission_required = "view_article"
    allowed_exports = ["csv"]

    def get_field_actions(self, obj):
        actions = list(self.action_links)
        if obj.published:
            actions.pop(1)  # delete
        return actions

    def get_category_field(self, row_instance):
        return row_instance.category.name

    def get_published_field(self, row_instance):
        symbol = "fa-check" if row_instance.published else "fa-minus"
        return mark_safe('<i class="fa {}"></i>'.format(symbol))

    def get_category_ordering_field(self):
        return "category__name"

    def get_published_field_classes(self, row_instance):
        return "online" if row_instance.published else "offline"


class ArticleUpdateView(UpdateView):
    page_title = _("Edit Article")