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

from classytags.arguments import Argument
from classytags.core import Options, Tag
from classytags.helpers import InclusionTag
from cms.constants import PUBLISHER_STATE_PENDING

from django import template
from django.conf import settings
from django.contrib.admin.views.main import ERROR_FLAG
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _


register = template.Library()

CMS_ADMIN_ICON_BASE = "%sadmin/img/" % settings.STATIC_URL


@register.simple_tag(takes_context=True)
def show_admin_menu_for_pages(context, descendants, depth=1):
    admin = context['admin']
    request = context['request']

    if 'tree' in context:
        filtered = context['tree']['is_filtered']
    else:
        filtered = False

    rows = admin.get_tree_rows(
        request,
        pages=descendants,
        language=context['preview_language'],
        depth=depth,
        follow_descendants=not bool(filtered),
    )
    return mark_safe(''.join(rows))


class TreePublishRow(Tag):
    name = "tree_publish_row"
    options = Options(
        Argument('page'),
        Argument('language')
    )

    def render_tag(self, context, page, language):
        page_pending_publication = page.get_publisher_state(language) == PUBLISHER_STATE_PENDING

        if page.is_published(language) and not page_pending_publication:
            if page.is_dirty(language):
                cls = "cms-pagetree-node-state cms-pagetree-node-state-dirty dirty"
                text = _("unpublished changes")
            else:
                cls = "cms-pagetree-node-state cms-pagetree-node-state-published published"
                text = _("published")
        else:
            page_languages = page.get_languages()

            if language in page_languages:
                if page_pending_publication:
                    cls = "cms-pagetree-node-state cms-pagetree-node-state-unpublished-parent unpublishedparent"
                    text = _("unpublished parent")
                else:
                    cls = "cms-pagetree-node-state cms-pagetree-node-state-unpublished unpublished"
                    text = _("unpublished")
            else:
                cls = "cms-pagetree-node-state cms-pagetree-node-state-empty empty"
                text = _("no content")
        return mark_safe(
            '<span class="cms-hover-tooltip cms-hover-tooltip-left cms-hover-tooltip-delay %s" '
            'data-cms-tooltip="%s"></span>' % (cls, force_text(text)))


register.tag(TreePublishRow)


@register.filter
def is_published(page, language):
    if page.is_published(language):
        return True

    page_languages = page.get_languages()