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

from django.shortcuts import render_to_response
from django.template import RequestContext
from hdabo.models import Datasheet, TaggedSheet
import re

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)
    )
