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

@author: tc
'''
from datetime import datetime
from django.conf import settings
from django.views.generic import ListView, DetailView, View
from django.shortcuts import redirect, get_object_or_404
from p4l.forms import RecordFilterForm
from p4l.models import Record
from p4l.utils import get_labels_for_uris
import json
import logging


logger = logging.getLogger(__name__)

class RecordListView(ListView):
    
    queryset = Record.objects.select_related("language").prefetch_related('titles', 'imprints').order_by('identifier')  # @UndefinedVariable
    paginate_by = settings.NB_RECORDS_BY_PAGE
    template_name = "p4l/p4l_home.html"
    form_class = RecordFilterForm
    
    def get_context_data(self, **kwargs):
        context = ListView.get_context_data(self, **kwargs)
        context['filter_form'] = self.form_class()
        # Add filter params from GET params
        filter_params = {}
        if 'title' in self.request.GET:
            filter_params['title'] = self.request.GET['title']
        context['filter_params'] = filter_params
        return context
    
    def get_queryset(self):
        qs = super(RecordListView, self).get_queryset()
        filter_form = self.form_class(self.request.GET)
        if filter_form.is_valid():
            return filter_form.get_filter_qs(qs)
        else:
            return qs


class RecordDetailView(DetailView):
    
    model = Record
    template_name = "p4l/p4l_record_view.html"
    slug_field = "identifier"
    
    def get_context_data(self, **kwargs):
        context = DetailView.get_context_data(self, **kwargs)
        # We get the language, "fr" by default
        lang = "fr"
        if "lang" in self.request.GET:
            lang = self.request.GET["lang"]
        elif hasattr(self.request, "LANGUAGE_CODE") and self.request.LANGUAGE_CODE in ["fr","en","es"]:
            lang = self.request.LANGUAGE_CODE
        # self.object is the record entry
        # We get the subjects'labels with the Thesaurus repository
        uri_list = [s.uri for s in self.object.subjects.all()]
        uris_labels = get_labels_for_uris(uri_list, "http://skos.um.es/unescothes/CS000", lang, False)
        context['subjects_labels'] = uris_labels
        # We get the themes'labels with the Themes repository
        uri_list = [s.uri for s in self.object.themes.all()]
        uris_labels = get_labels_for_uris(uri_list, "http://www.iiep.unesco.org/plan4learning/scheme/Themes", lang, False)
        context['themes_labels'] = uris_labels
        # We get the countries'labels with the Thesaurus repository
        uri_list = [s.uri for s in self.object.countries.all()]
        uris_labels = get_labels_for_uris(uri_list, "http://skos.um.es/unescothes/CS000/Countries", lang, False)
        context['countries_labels'] = uris_labels
        # We get the languages'labels with the Languages repository
        if self.object.language:
            uri_list = [self.object.language.uri]
            uris_labels = get_labels_for_uris(uri_list, "http://www.iiep.unesco.org/plan4learning/scheme/Languages", lang, False)
            context['language_label'] = uris_labels[self.object.language.uri]
        # We get the other languages'labels with the Languages repository
        uri_list = [s.uri for s in self.object.otherLanguages.all()]
        uris_labels = get_labels_for_uris(uri_list, "http://www.iiep.unesco.org/plan4learning/scheme/Languages", lang, False)
        context['otherLanguages_labels'] = uris_labels
        # We get the project'labels with the Projects repository
        uri_list = [s.uri for s in self.object.projectNames.all()]
        uris_labels = get_labels_for_uris(uri_list, "http://www.iiep.unesco.org/plan4learning/scheme/Projects", None, True)
        context['projects_labels'] = uris_labels
        # We get the subjectCorporateBodies'labels with the Organizations repository
        uri_list = [s.uri for s in self.object.subjectCorporateBodies.all()]
        uris_labels = get_labels_for_uris(uri_list, "http://www.iiep.unesco.org/plan4learning/scheme/Organizations", None, True)
        context['subjectCorporateBodies_labels'] = uris_labels
        # We get the corporateAuthors'labels with the Organizations repository
        uri_list = [s.uri for s in self.object.corporateAuthors.all()]
        uris_labels = get_labels_for_uris(uri_list, "http://www.iiep.unesco.org/plan4learning/scheme/Organizations", None, True)
        context['corporateAuthors_labels'] = uris_labels
        # We get the recordType'labels with the DocumentType repository
        if self.object.recordType:
            uri_list = [self.object.recordType]
            uris_labels = get_labels_for_uris(uri_list, "http://www.iiep.unesco.org/plan4learning/scheme/DocumentType", lang, False)
            context['recordType_label'] = uris_labels[self.object.recordType]
        
        return context

class RecordEditView(DetailView):
    http_method_names = ['get']
    template_name = 'p4l/record_update_form.html'
    model = Record
    slug_field = "identifier"

    def get_context_data(self, **kwargs):
        context = DetailView.get_context_data(self, **kwargs)
        # We get the language, "fr" by default
        lang = "fr"
        if "lang" in self.request.GET:
            lang = self.request.GET["lang"]
        elif hasattr(self.request, "LANGUAGE_CODE") and self.request.LANGUAGE_CODE in ["fr","en","es"]:
            lang = self.request.LANGUAGE_CODE
        
        uri_labels = get_labels_for_uris([s.uri for s in self.object.subjects.all()], "http://skos.um.es/unescothes/CS000", lang, False)
        uri_labels.update(get_labels_for_uris([s.uri for s in self.object.themes.all()], "http://www.iiep.unesco.org/plan4learning/scheme/Themes", lang, False))
        uri_labels.update(get_labels_for_uris([s.uri for s in self.object.countries.all()], "http://skos.um.es/unescothes/CS000/Countries", lang, False))
        uri_labels.update(get_labels_for_uris([self.object.language.uri] if self.object.language else [], "http://www.iiep.unesco.org/plan4learning/scheme/Languages", lang, False))
        uri_labels.update(get_labels_for_uris([s.uri for s in self.object.otherLanguages.all()], "http://www.iiep.unesco.org/plan4learning/scheme/Languages", lang, False))
        uri_labels.update(get_labels_for_uris([s.uri for s in self.object.projectNames.all()], "http://www.iiep.unesco.org/plan4learning/scheme/Projects", None, True))
        uri_labels.update(get_labels_for_uris([s.uri for s in self.object.subjectCorporateBodies.all()], "http://www.iiep.unesco.org/plan4learning/scheme/Organizations", None, True))
        uri_labels.update(get_labels_for_uris([s.uri for s in self.object.corporateAuthors.all()], "http://www.iiep.unesco.org/plan4learning/scheme/Organizations", None, True))
        uri_labels.update(get_labels_for_uris([self.object.recordType] if self.object.recordType else [], "http://www.iiep.unesco.org/plan4learning/scheme/DocumentType", lang, False))
        context['uri_labels'] = json.dumps(uri_labels)
        
        # lang must be like "XX" in the sparql request 
        lang = '"' + lang + '"'
        query_dicts = {
            'subjects': {
                'dataurl': settings.SPARQL_QUERY_ENDPOINT,
                'dataquery': settings.SPARQL_SUBJECT_QUERIES["filter"] % (lang, lang),
                'datarootquery': settings.SPARQL_SUBJECT_QUERIES["root"] % lang,
                'datachildsquery': settings.SPARQL_SUBJECT_QUERIES["childs"] % lang,
                'datachildcountquery': settings.SPARQL_SUBJECT_QUERIES["child-count"]
            },
            'themes' : {
                'dataurl': settings.SPARQL_QUERY_ENDPOINT,
                'dataquery': settings.SPARQL_THEME_QUERIES["filter"] % (lang, lang),
                'datarootquery': settings.SPARQL_THEME_QUERIES["root"] % lang,
                'datachildsquery': settings.SPARQL_THEME_QUERIES["childs"] % lang,
                'datachildcountquery': settings.SPARQL_THEME_QUERIES["child-count"]
            },
            'countries' : {
                'dataurl': settings.SPARQL_QUERY_ENDPOINT,
                'dataquery': settings.SPARQL_COUNTRY_QUERIES["filter"] % (lang, lang),
                'datarootquery': settings.SPARQL_COUNTRY_QUERIES["root"] % lang,
                'datachildsquery': settings.SPARQL_COUNTRY_QUERIES["childs"] % lang,
                'datachildcountquery': settings.SPARQL_COUNTRY_QUERIES["child-count"]
            },
            'languages' : {
                'dataurl': settings.SPARQL_QUERY_ENDPOINT,
                'dataquery': settings.SPARQL_LANGUAGE_QUERIES["filter"] % (lang, lang),
                'datarootquery': settings.SPARQL_LANGUAGE_QUERIES["root"] % lang,
                'datachildsquery': "",
                'datachildcountquery': ""
            },
            'projects' : {
                'dataurl': settings.SPARQL_QUERY_ENDPOINT,
                'dataquery': settings.SPARQL_PROJECT_QUERIES["filter"],
                'datarootquery': settings.SPARQL_PROJECT_QUERIES["root"],
                'datachildsquery': "",
                'datachildcountquery': ""
            },
            'organizations' : {
                'dataurl': settings.SPARQL_QUERY_ENDPOINT,
                'dataquery': settings.SPARQL_ORGANIZATION_QUERIES["filter"],
                'datarootquery': settings.SPARQL_ORGANIZATION_QUERIES["root"],
                'datachildsquery': "",
                'datachildcountquery': ""
            },
            'types' : {
                'dataurl': settings.SPARQL_QUERY_ENDPOINT,
                'dataquery': settings.SPARQL_TYPE_QUERIES["filter"] % (lang, lang),
                'datarootquery': settings.SPARQL_TYPE_QUERIES["root"] % lang,
                'datachildsquery': "",
                'datachildcountquery': ""
            }
        }
        context['query_dicts'] = json.dumps(query_dicts)
        
        # Languages list used in drop down list
        context['languages_list'] = json.dumps(settings.LANGUAGES_LIST)
                
        return context


class RecordNewView(View):
    def get(self, request, *args, **kwargs):
        rec = Record()
        rec.identifier = "T" + datetime.now().strftime("%Y%m%d%H%M%S")
        rec.uri = "http://www.iiep.unesco.org/plan4learning/record/" + rec.identifier
        rec.save()
        return redirect('p4l_record_edit', rec.identifier)


class RecordDeleteView(View):
    def get(self, request, slug, **kwargs):
        rec = get_object_or_404(Record, identifier=slug)
        rec.delete()
        return redirect('p4l_home')
        