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

@author: rvelt
'''

from jocondelab.models import DbpediaYears, DbpediaGeo, DbpediaFields, ContributedTerm, ContributedFields, Contribution
from core.models import Notice, Term, Thesaurus
import django.utils.simplejson as json
from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.db.models import Sum
from django.conf import settings
from jocondelab.views.front_office import get_notices

def terms(request):
    
    lang = request.GET.get('lang', request.LANGUAGE_CODE)[:2]
    q = request.GET.get('term', None)
    count = request.GET.get('count', 20)
    qs = DbpediaFields.objects.filter(language_code=lang,label__istartswith=q).values('dbpedia_uri','label').distinct().order_by('label')[:count]
    res = [{"dbpedia_uri": r['dbpedia_uri'], "label": r['label']} for r in qs]
    return HttpResponse(content=json.dumps(res), mimetype='application/json')

def years(request):
    
    lang = request.GET.get('lang', request.LANGUAGE_CODE)[:2]
    from_year = request.GET.get('from_year', None)
    to_year = request.GET.get('to_year', None)
    count = request.GET.get('count', 20)
    
    qs = DbpediaYears.objects.filter(term__dbpedia_fields__language_code=lang)
    if to_year:
        qs = qs.filter(start_year__lte=to_year)
    if from_year:
        qs = qs.filter(end_year__gte=from_year)
    qs = qs.values('start_year','end_year','term__dbpedia_fields__label','term__dbpedia_uri')
    qs = qs.annotate(sum_notices=Sum('term__nb_notice')).order_by('-sum_notices')
    
    qs = qs[:count]
    
    results = [{
                "start_year": y["start_year"],
                "end_year": y["end_year"],
                "label": y["term__dbpedia_fields__label"],
                "sum_notices": y["sum_notices"],
                "dbpedia_uri": y["term__dbpedia_uri"]
                } for y in qs]
    
    return HttpResponse(content=json.dumps(results), mimetype='application/json')

def geo_coords(request):
    
    lang = request.GET.get('lang', request.LANGUAGE_CODE)[:2]
    min_lat = request.GET.get('min_lat', None)
    max_lat = request.GET.get('max_lat', None)
    min_lng = request.GET.get('min_lng', None)
    max_lng = request.GET.get('max_lng', None)
    count = request.GET.get('count', 20)
    
    qs = DbpediaGeo.objects.filter(term__dbpedia_fields__language_code=lang)
    
    if min_lat:
        qs = qs.filter(latitude__gt=min_lat)
    if max_lat:
        qs = qs.filter(latitude__lt=max_lat)
    if min_lng:
        qs = qs.filter(longitude__gt=min_lng)
    if max_lng:
        qs = qs.filter(longitude__lt=max_lng)
    
    qs = qs.values('latitude','longitude','term__dbpedia_fields__label','term__dbpedia_uri')
    qs = qs.annotate(sum_notices=Sum('term__nb_notice')).order_by('-sum_notices')
    
    qs = qs[:count]
    
    results = [{
                "latitude": y["latitude"],
                "longitude": y["longitude"],
                "label": y["term__dbpedia_fields__label"],
                "sum_notices": y["sum_notices"],
                "dbpedia_uri": y["term__dbpedia_uri"]
                } for y in qs]
    
    return HttpResponse(content=json.dumps(results), mimetype='application/json')

def contents(request):
    
    lang = request.GET.get('lang', request.LANGUAGE_CODE)[:2]
    count = request.GET.get('count', 24)
    random = ("random" in request.GET and request.GET["random"])
    format = request.GET.get('format', 'text/html')
    term_id = request.GET.get('term_id', None)
    dbpedia_uri = request.GET.get('dbpedia_uri', None)
    
    qs = Notice.objects.filter(image=True)
    searchlabel = ""
    termobj = None
    if term_id:
        qs = qs.filter(noticeterm__term_id=term_id)
        termobj = Term.objects.get(id=term_id)
    if dbpedia_uri:
        qs = qs.filter(noticeterm__term__dbpedia_uri=dbpedia_uri)
        termobj = Term.objects.filter(dbpedia_uri=dbpedia_uri)[0]
    rescount = qs.count()
    if random:
        qs = qs.order_by('?')
    results = get_notices(qs[:count], lang)
    if termobj:
        termtrans = termobj.dbpedia_fields.filter(language_code = lang)
        searchlabel = termtrans[0].label if termtrans.count() else termobj.label
    
    context = {
               "searchterm": searchlabel,
               "count": rescount,
               "notices": results
            }
    
    if format == 'text/html':
        return TemplateResponse(request, 'jocondelab/ajax_contents.html', context )
    
    if format == 'application/json':
        return HttpResponse(content=json.dumps(context), mimetype='application/json')
    
    return HttpResponse(status=400, content='Unknown Format')

def geo_search(request):
    
    lang = request.GET.get('lang', request.LANGUAGE_CODE)[:2]
    q = request.GET.get('term', None)
    count = request.GET.get('count', 20)
    
    qs = DbpediaGeo.objects.filter(term__dbpedia_fields__language_code=lang, term__dbpedia_fields__label__istartswith=q)
    qs = qs.values('latitude','longitude','term__dbpedia_fields__label','term__dbpedia_uri')
    qs = qs.annotate(sum_notices=Sum('term__nb_notice')).order_by('-sum_notices')[:count]
    
    results = [{
                "latitude": y["latitude"],
                "longitude": y["longitude"],
                "label": y["term__dbpedia_fields__label"],
                "sum_notices": y["sum_notices"],
                "dbpedia_uri": y["term__dbpedia_uri"]
                } for y in qs]
    results.sort(key=lambda y: y["label"])
    
    return HttpResponse(content=json.dumps(results), mimetype='application/json')

def contribute(request):
    
    notice_id = request.POST.get('notice_id', None)
    dbpedia_language = request.POST.get('dbpedia_language', None)
    dbpedia_uri = request.POST.get('dbpedia_uri', None)
    thesaurus_label = request.POST.get('thesaurus_label', None)
    translations = json.loads(request.POST.get('translations', '[]'))
    
    thobj = Thesaurus.objects.get(label=thesaurus_label)
    notobj = Notice.objects.get(id=notice_id)
    termobj, created = ContributedTerm.objects.get_or_create(dbpedia_uri=dbpedia_uri, dbpedia_language=dbpedia_language)
    controbj, created = Contribution.objects.get_or_create(term=termobj, thesaurus=thobj, notice=notobj, defaults={'contribution_count': 1})
    if not created:
        controbj.contribution_count += 1
        controbj.save()
    for t in translations:
        fieldsobj, created = ContributedFields.objects.get_or_create(term=termobj, dbpedia_uri=dbpedia_uri, language_code=t['language'], defaults={'abstract': t['abstract'], 'label': t['label'], 'thumbnail': t['thumbnail']})
        if not created:
            fieldsobj.abstract = t['abstract']
            fieldsobj.thumbnail = t['thumbnail']
            fieldsobj.label = t['label']
            fieldsobj.save()

    return HttpResponse(content=json.dumps(translations), mimetype='application/json')
    