# -*- coding: utf-8 -*-

import re

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.base import TemplateView
from django.conf import settings
import user_agents

from hdabo.models import Datasheet, TaggedSheet
from django.http.response import Http404


def datasheet(request, hda_id=None):
    """
    Methode Vue affichant le détail d'une fiche HDA.
    Cette vue affiche en fait un résumé de la notice mise en relation avec les notices liées, via les mots clefs.
    """
    MAX_TAG = 15
    MAX_RELATED = 50

    datasheet = None
    try:
        datasheet = Datasheet.objects.select_related("organisation").get(hda_id=hda_id)
    except Datasheet.DoesNotExist:
        raise Http404("The datasheet %s is not found."%hda_id)

    domain = re.findall(r"^https?://(www\.)?([^/]+)",datasheet.url)
    ordered_tags = TaggedSheet.objects.filter(datasheet=datasheet,order__lte=MAX_TAG).select_related("tag").order_by('order')
    tags = [t.tag.id for t in ordered_tags]
    tagorders = dict([(t.tag.id,t.order) for t in ordered_tags])
    tsqs = TaggedSheet.objects.exclude(datasheet=datasheet).filter(order__lte=MAX_TAG,tag_id__in=tags)
    dsscores = {}
    addtoscore = 2*MAX_TAG

    for ts in tsqs:
        a_order = tagorders[ts.tag_id]
        b_order = ts.order
        score = addtoscore - a_order - b_order
        dsscore = dsscores.get(ts.datasheet_id,0)
        dsscores[ts.datasheet_id] = dsscore + score
    relatedqs = Datasheet.objects.filter(id__in=dsscores.keys()).select_related("organisation")
    relatedds = [{
        'id': ds.id,
        'hda_id': ds.hda_id,
        'title': ds.title,
        'description': ds.description,
        'organisation_name': ds.organisation.name if ds.organisation else '',
        'organisation_url': ds.organisation.website if ds.organisation else '',
        'score': dsscores.get(ds.id,0),
    } for ds in relatedqs]
    relatedds = sorted(relatedds, key=lambda ds: -ds['score'])[:MAX_RELATED]

    for ds in relatedds:
        otqs = TaggedSheet.objects.filter(datasheet_id=ds['id'],order__lte=MAX_TAG).select_related("tag").order_by('order')
        ds['ordered_tags'] = [{
            'id': t.tag.id,
            'label': t.tag.label,
            'order': t.order,
            'common' : (t.tag.id in tags)
        } for t in otqs]

    return render_to_response(
        "notice.html",
        {
            'datasheet':datasheet,
            'domain': domain[0][1] if domain else "",
            'ordered_tags': ordered_tags,
            'related': relatedds,
        },
        context_instance=RequestContext(request)
    )


class HdalabAboutPage(TemplateView):
    """
    Classe de vue en charge de l'affichage de la page à propos.
    C'est une simple django.views.generic.TemplateView qui ajoute quelques informations dans le contexte de rendu du template.
    """

    template_name = "a_propos.html"

    def get_context_data(self, **kwargs):
        context = super(HdalabAboutPage, self).get_context_data(**kwargs)
        ua_str = self.request.META.get('HTTP_USER_AGENT', '')
        ua = user_agents.parse(ua_str)
        context['add_kanji_font'] = (ua.os.family in settings.OLDER_WINDOWS)
        context['tutorial_video_urls'] = getattr(settings, 'RENKAN_TUTORIAL_VIDEO_URLS', [])

        return context
