# -*- 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
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)
        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["rescount"] = nbnotices
        context["notices"] = get_notices(ns, lang)
        context["queryterms"] = 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(View, TemplateResponseMixin):
    
    template_name = "jocondelab/front_notice.html"
    
    def get(self, request, notice_id):
        
        context = {}
        lang = request.GET.get('lang',request.LANGUAGE_CODE)
        
        notice = Notice.objects.get(id=notice_id)
        
        context["lang"] = lang
        context["notice"] = notice
        context["title"] = notice.titr if notice.titr else notice.deno
        context["images"] = [i.url for i in notice.images.exclude(relative_url__endswith='v.jpg')]
        terms = []
        for nt in notice.noticeterm_set.select_related('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
        context['JOCONDE_IMG_BASE_URL'] = settings.JOCONDE_IMG_BASE_URL
        
        return self.render_to_response(context)

    