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

@author: rvelt
'''

from core.models import (Notice, Thesaurus, Term)
from jocondelab.models import DbpediaFields
from django.conf import settings
from django.views.generic import View, DetailView
from django.views.generic.base import TemplateResponseMixin
from django.db.models import Q, Count
import re
import time

def get_notices(noticeset, lang):
    notices = []
    thesauruscache = {t.id: t.label for t in Thesaurus.objects.all()}
    for n in noticeset:
        terms = [{
            "locale_label": ts.term.dbpedia_fields.get(language_code=lang).label,
            "thesaurus": thesauruscache[ts.term.thesaurus_id],
            "dbpedia_uri": ts.term.dbpedia_uri
        } for ts in n.noticeterm_set.filter(term__dbpedia_fields__language_code=lang)]
        termsbythesaurus = {}
        for term in terms:
            if not term["thesaurus"] in termsbythesaurus:
                termsbythesaurus[term["thesaurus"]] = []
            termsbythesaurus[term["thesaurus"]].append(term)
        noticedict = {
            "id": n.id,
            "imagetitle": n.titr if n.titr else n.deno,
            "title": n.titr,
            "denomination": n.deno,
            "image": (settings.JOCONDE_IMG_BASE_URL + n.images.all()[0].url) if n.images.count() else "",
            "authors": re.split("\s?;\s?", n.autr) if n.autr else [],
            "terms_by_thesaurus": termsbythesaurus
        }
        notices.append(noticedict)
    return notices

class SearchView(View, TemplateResponseMixin):
    
    template_name = "jocondelab/front_search.html"
    
    def get(self, request):
        
        starttime = time.time()
        
        context = {}
        lang = request.GET.get('lang',request.LANGUAGE_CODE)[:2]
        querystr = request.GET.get('q', "")
        search_in_title = request.GET.get('search_in_title', True)
        search_in_translations = request.GET.get('search_in_translations', True)
        show_tagcloud = request.GET.get('show_tagcloud', True)
        queryterms = [s.strip(" ") for s in re.split("[,;]",querystr) if s.strip(" ")] if (search_in_title or search_in_translations) else None
        
        npp = 48 if queryterms else 24
        
        if queryterms and search_in_translations and search_in_title:
            mainq = Q()
            if search_in_translations:
                transq = Q()
                for term in queryterms:
                    transq = transq | Q(label__icontains=term)
                ts = DbpediaFields.objects.filter(language_code=lang).filter(transq).values('term_id')
                mainq = mainq | Q(noticeterm__term__in=ts)
#                     mainq = mainq | Q(noticeterm__term__dbpedia_fields__language_code=lang,noticeterm__term__dbpedia_fields__label__icontains=term)
            if search_in_title:
                for term in queryterms:
                    mainq = mainq | Q(titr__icontains=term)
            qs = Notice.objects.filter(Q(image=True) & mainq).distinct()
            nbnotices = qs.count()
            ns = qs[:npp]
        else:
            qs = Notice.objects.filter(image=True)
            nbnotices = qs.count()
            ns = qs.order_by('?')[:npp]
        
        context["lang"] = lang
        context["count"] = nbnotices
        context["notices"] = get_notices(ns, lang)
        context["searchterm"] = querystr
        
        wpp = 50
        if show_tagcloud:
            ts = Term.objects.filter(dbpedia_fields__language_code=lang).order_by('-nb_notice')[:wpp]
            words = [{
                "uri": t.dbpedia_uri,
                "label": t.dbpedia_fields.get(language_code=lang).label,
                "notice_count": t.nb_notice
            } for t in ts]
        else:
            words = []
        if words:
            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
        
        context['duration'] = "%.2f"%(time.time() - starttime)
        
        return self.render_to_response(context)

class NoticeView(DetailView):
    
    model = Notice
    template_name = "jocondelab/front_notice.html"
    
    def get_context_data(self, **kwargs):
        
        context = super(NoticeView, self).get_context_data(**kwargs)
        lang = self.request.GET.get('lang',self.request.LANGUAGE_CODE)[:2]
        
        context["lang"] = lang
        context["images"] = [settings.JOCONDE_IMG_BASE_URL + i.url for i in self.object.images.exclude(relative_url__endswith='v.jpg')]
        context["title"] = self.object.titr if self.object.titr else self.object.deno
        
        terms = []
        for nt in self.object.noticeterm_set.select_related('term__dbpedia_fields').all():
            translated_term = nt.term.dbpedia_fields.filter(language_code = lang)
            termdict = {
                "label": nt.term.label,
                "thesaurus": nt.term.thesaurus.label,
                "dbpedia_uri": nt.term.dbpedia_uri,
                "translated": True if translated_term else False,
                "locale_label": translated_term[0].label if translated_term else nt.term.label
            }
            terms.append(termdict)
        termsbythesaurus = {}
        for term in terms:
            if not term["thesaurus"] in termsbythesaurus:
                termsbythesaurus[term["thesaurus"]] = {
                   "translated": [],
                   "untranslated": []
                   }
            termsbythesaurus[term["thesaurus"]]["translated" if term["translated"] else "untranslated"].append(term)
         
        context["terms_by_thesaurus"] = termsbythesaurus
        
        return context

    