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

@author: rvelt
'''

from core.models import (Notice, Thesaurus, Term)
from jocondelab.models import (DbpediaFields, Country)
from django.core.paginator import Paginator
import django.utils.simplejson as json
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

class SearchView(View, TemplateResponseMixin):
    
    def get(self, request):
                
        context = {}
        lang = request.GET.get('lang',request.LANGUAGE_CODE)[:2]
        page = request.GET.get('page',1)
        querystr = request.GET.get('q', "")
        is_ajax = request.is_ajax()
        queryterms = [s.strip(" ") for s in re.split("[,;]",querystr) if s.strip(" ")]
        dbpedia_uri = request.GET.get('dbpedia_uri', None)
        emptysearch = (not queryterms and not dbpedia_uri)
        show_tagcloud = (emptysearch and not is_ajax)
        npp = request.GET.get('count', 12 if emptysearch else 36)
        wpp = 50
        context["current_page"] = page
        context["lang"] = lang
        
        if self.template_name is None:
            if is_ajax and page > 1:
                self.template_name = "jocondelab/partial/notice_list.html"
            else:
                if is_ajax:
                    self.template_name = "jocondelab/partial/wrapped_notice_list.html"
                else:
                    self.template_name = "jocondelab/front_search.html"
        
        qs = Notice.objects.filter(image=True)
        if emptysearch:
            context["count"] = qs.count()
            ns = qs.order_by('?')[:npp]
        else:
            if dbpedia_uri:
                qs = qs.filter(noticeterm__term__dbpedia_uri=dbpedia_uri)
                if page == 1:
                    termobj = Term.objects.filter(dbpedia_uri=dbpedia_uri)[0]
                    if termobj:
                        termtrans = termobj.dbpedia_fields.filter(language_code = lang)
                        context["searchterm"] = termtrans[0].label if termtrans.count() else termobj.label
            if queryterms:
                context["searchterm"] = querystr
                for term in queryterms:
                    fs = DbpediaFields.objects.filter(label=term, language_code=lang).values('term_id').distinct()
                    qs = qs.filter(noticeterm__term__in=fs)
            qs = qs.distinct()
            paginator = Paginator(qs, npp)
            context["count"] = paginator.count
            ns = paginator.page(page)
            context["page_count"] = paginator.num_pages
        
        notices = []
        thesauruscache = {th.id: th.label for th in Thesaurus.objects.all()}
        for n in ns:
            terms = [{
                "locale_label": t.dbpedia_fields.get(language_code=lang).label,
                "thesaurus": thesauruscache[t.thesaurus_id],
                "dbpedia_uri": t.dbpedia_uri
            } for t in Term.objects.filter(noticeterm__notice=n,dbpedia_fields__language_code=lang).distinct()]
            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)
        context["notices"] = notices
        
        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]
            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
                
        return self.render_to_response(context)

class GeoView(View, TemplateResponseMixin):
    
    template_name = "jocondelab/front_geo.html"
    
    def get(self, request):
        
        context = {}
        cqs = Country.objects.order_by('-nb_notices')
        context["countries"] = json.dumps([c for c in cqs.values('dbpedia_uri','iso_code_3','nb_notices')])
        
        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
        
        termsbythesaurus = {}
        for nt in Term.objects.filter(noticeterm__notice=self.object).select_related('thesaurus,dbpedia_fields').distinct():
            translated_term = nt.dbpedia_fields.filter(language_code = lang)
            term = {
                "thesaurus": nt.thesaurus.label,
                "dbpedia_uri": nt.dbpedia_uri,
                "translated": True if translated_term else False,
                "label": translated_term[0].label if translated_term else nt.label
            }
            if not term["thesaurus"] in termsbythesaurus:
                termsbythesaurus[term["thesaurus"]] = {
                   "translated": [],
                   "untranslated": []
                   }
            termsbythesaurus[term["thesaurus"]]["translated" if term["translated"] else "untranslated"].append(term)
        
        cqs = self.object.contribution_set.select_related('term__dbpedia_fields')
        contributions = [{
                "label": ct.term.dbpedia_fields.get(language_code=lang).label,
                "dbpedia_uri": ct.term.dbpedia_uri,
                "contribution_id": ct.id
            } for ct in cqs.filter(thesaurus=None,term__dbpedia_fields__language_code=lang).order_by('-contribution_count')]
            
        context["terms_by_thesaurus"] = termsbythesaurus
        context["contributions"] = contributions
        context['wikipedia_urls'] = json.dumps(settings.WIKIPEDIA_URLS)
        context['JOCONDE_NOTICE_BASE_URL'] = settings.JOCONDE_NOTICE_BASE_URL
        
        return context
    
    def get_object(self):
        if self.pk_url_kwarg in self.kwargs:
            return super(NoticeView, self).get_object()
        else:
            queryset = self.get_queryset().filter(image=True, repr='')
            return queryset.order_by('?')[0]
    