# -*- coding: utf-8 -*-
'''
Created on Aug 08, 2013

@author: rvelt
'''

from core.models import Notice
from jocondelab.models import DbpediaResource, DbpediaTranslation
from django.conf import settings
from django.views.generic import View
from django.views.generic.base import TemplateResponseMixin
import random

class MultilingualSearch(View, TemplateResponseMixin):
    
    template_name = "jocondelab/front_search.html"
    
    def get(self, request):
        
        context = {}
        lang = request.GET.get('lang',request.LANGUAGE_CODE)
        queryterms = request.GET.get('q', None)
        
        npp = 12
        notices = []
        
        qs = Notice.objects.filter(image=True)
        
        nbnotices = qs.count()
        subrangelength = 2
        
        locale_labels = {}
        
        while len(notices) < npp:
            offset = int(random.random()*(nbnotices-subrangelength))
            ns = qs[offset:(offset+subrangelength)].select_related('images','noticeterm_set__term__thesaurus')
            for n in ns:
                terms = [{
                    "label": ts.term.label,
                    "dbpedia_uri": ts.term.dbpedia_uri,
                    "thesaurus": ts.term.thesaurus.label
                } for ts in n.noticeterm_set.all()]
                for term in terms:
                    if term["dbpedia_uri"]:
                        locale_labels[term["dbpedia_uri"]] = None
                noticedict = {
                    "id": n.id,
                    "imagetitle": n.titr if n.titr else n.deno,
                    "title": n.titr,
                    "denomination": n.deno,
                    "image": n.images.all()[0].url,
                    "author": n.autr,
                    "all_terms": terms
                }
                notices.append(noticedict)
        
        llqs = DbpediaTranslation.objects.select_related('dbpediaresource').filter(lang = lang, dbpediaresource__uri__in=[term["dbpedia_uri"] for term in terms])
        locale_labels = {
            ll.dbpediaresource.uri: ll.label for ll in llqs
        }
        for n in notices:
            termsbythesaurus = {}
            for term in n["all_terms"]:
                if term["dbpedia_uri"] in locale_labels:
                    term["locale_label"] = locale_labels[term["dbpedia_uri"]]
                    if not term["thesaurus"] in termsbythesaurus:
                        termsbythesaurus[term["thesaurus"]] = []
                    termsbythesaurus[term["thesaurus"]].append(term)
            n["terms_by_thesaurus"] = termsbythesaurus
                
        random.shuffle(notices)
        
        context["lang"] = lang
        context["rescount"] = nbnotices
        context["notices"] = notices
        context["translations"] = locale_labels
        
        wpp = 30
        
        wqs = DbpediaResource.objects.select_related('translations').filter(translations__lang=lang)
        wqs = wqs.extra(select = {
            "notice_count": "SELECT COUNT(DISTINCT(core_noticeterm.id)) FROM core_noticeterm JOIN core_term ON core_term.id = core_noticeterm.term_id WHERE core_term.dbpedia_uri = jocondelab_dbpediaresource.uri"
        }).order_by("-notice_count")[:wpp]
        
        words = [{
            "uri": w.uri,
            "label": w.translations.get(lang=lang).label,
            "notice_count": w.notice_count
        } for w in wqs]
        
        fontmax = 2.5
        fontmin = 1.
        scale = (fontmax - fontmin)/max(1,words[0]["notice_count"]-words[-1]["notice_count"])
        
        for w in words:
            w["font_size"] = fontmin + scale * w["notice_count"]
        
        context["words"] = words
        
        context['JOCONDE_IMG_BASE_URL'] = settings.JOCONDE_IMG_BASE_URL
        
        return self.render_to_response(context)