from django.shortcuts import render
from django.utils.safestring import mark_safe
from django.urls import reverse

from django_project.settings import STATIC_URL
from tinywiki import settings
from .base import View
from django.http import HttpRequest, HttpResponse
from django.db.models.functions import Lower
import string
from ..models import Page
from ..enums import WikiPageStatus
from django.utils.translation import ngettext, gettext as _

# Create your views here.

class HomeView(View):
    template_name = "tinywiki/home/home.html"

    def get(self,request):
        try:
            page = Page.objects.get(slug='tw-home')
            if (not Page.status == WikiPageStatus.PUBLISHED
                and not request.user.is_staff
                and not request.user.has_perm('page.view-all')):
                page = None

        except Page.DoesNotExist:
            page = None
        if self.user_can_create_system_pages:
            if settings.USE_BOOTSTRAP:
                create_tw_home = f"<a class=\"icon-link icon-link-hover\" href={reverse("tinywiki:page",kwargs={'slug':'tw-home'})}>{_('create a new page with the slug <i>tw-home</i>')}<svg class=\"bi\"><use xlink:href=\"{settings.settings.STATIC_URL + 'tinywiki/icons/bootstrap-icons.svg' }#house-add\" ></use></svg></a>"
            else:
                create_tw_home = f"<a href={reverse("tinywiki:page",kwargs={'slug':'tw-home'})}>{_('create a new page with the slug <i>tw-home</i>')}</a>"
        else:
            create_tw_home = "create a new page with the slug <i>tw-home</i>"

        if settings.USE_BOOTSTRAP:
            markdown_guide = f"<a class=\"icon-link icon-link-hover\" href={reverse('tinywiki:page',kwargs={'slug':'tw-markdown'})}>{_('Guide for markdown used by TinyWiki')}<svg class=\"bi\"><use xlink:href=\"{settings.settings.STATIC_URL + 'tinywiki/icons/bootstrap-icons.svg' }#journal\"></use></svg></a>"
            bbcode_guide = f"<a class=\"icon-link icon-link-hover\" href={reverse('tinywiki:page',kwargs={'slug':'tw-bbcode'})}>{_('Guide for BBCode used by TinyWiki')}<svg class=\"bi\"><use xlink:href=\"{settings.settings.STATIC_URL + 'tinywiki/icons/bootstrap-icons.svg' }#journal\"></use></svg></a>"
        else:
            markdown_guide = f"<a class=\"icon-link icon-link-hover\" href={reverse('tinywiki:page',kwargs={'slug':'tw-markdown'})}>{_('Guide for markdown used by TinyWiki')}</a>"
            bbcode_guide = f"<a class=\"icon-link icon-link-hover\" href={reverse('tinywiki:page',kwargs={'slug':'tw-bbcode'})}>{_('Guide for BBCode used by TinyWiki')}</a>"
        return render(request,
                      self.get_template_name(),
                      self.get_context_data(page=page,
                                            user_can_create_system_pages=self.user_can_create_system_pages,
                                            create_tw_home=mark_safe(create_tw_home),
                                            markdown_guide=mark_safe(markdown_guide),
                                            bbcode_guide=mark_safe(bbcode_guide)))

class TocView(View):
    template_name = "tinywiki/home/wiki-content.html"
    bs_template_name = "tinywiki/home/bs-wiki-content.html"

    @classmethod
    def get_template_name(cls):
        if settings.USE_BOOTSTRAP:
            return cls.bs_template_name
        return cls.template_name

    def get(self,request):
        def mkdict(page:Page):
            return {'slug':page.slug,'title':page.title, 'is_system':page.slug.startswith('tw-')}

        user = self.request.user
        if (user.is_staff or user.has_perm('page.read_all')):
            pages = Page.objects.all()
        else:
            pages = Page.objects.filter(status_data=WikiPageStatus.PUBLISHED.value)

        toc_mapping = {}


        for page in pages:
            first_char = page.title.lstrip()[0].upper()
            if first_char.isdigit():
                if '0-9' not in toc_mapping:
                    toc_mapping['0-9'] = [mkdict(page)]
                else:
                    toc_mapping['0-9'].append(mkdict(page))
            elif first_char in string.punctuation:
                if '#' not in toc_mapping:
                    toc_mapping['#'] = [mkdict(page)]
                else:
                    toc_mapping['#'].append(mkdict(page))
            else:
                if first_char not in toc_mapping:
                    toc_mapping[first_char] = [mkdict(page)]
                else:
                    toc_mapping[first_char].append(mkdict(page))

        toc = []
        for key in sorted(toc_mapping.keys()):
            toc_entries = toc_mapping[key]
            count = len(toc_mapping[key])
            split = (count + 1) // 2
            pages_0 = toc_entries[:split]
            if split >= count:
                pages_1 = []
            else:
                pages_1 = toc_entries[split:]


            if (key.startswith('0') or key == '#'):
                toc_section = key
            else:
                toc_section = f"{key}..."

            toc_section = ngettext("{toc_section} ({n} page)","{toc_section} ({n} pages)", count).format(
                toc_section=toc_section,
                n=count,
            )
            toc.append((toc_section,pages_0,pages_1))

        return render(request,
                      self.get_template_name(),
                      self.get_context_data(toc=toc,subtitle=_("Table of Contents")))