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

import re

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

from hdabo.models import Datasheet, TaggedSheet


def datasheet(request, hda_id=None):
    MAX_TAG = 15
    MAX_RELATED = 50
    
    datasheet = Datasheet.objects.select_related("organisation").get(hda_id=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)
    )

OLDER_WINDOWS = [
    u'Windows', u'Windows Mobile', u'Windows XP',
    u'Windows ME', u'Windows 2000', u'Windows NT 4.0',
    u'Windows CE', u'Windows 95', u'Windows 98',
    u'Windows 3.1', u'Windows NT'
]

class HdalabAboutPage(TemplateView):
    
    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)
        if ua.os.family in OLDER_WINDOWS:
            context['add_kanji_font'] = True
        else:
            context['add_kanji_font'] = False

        return context
