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

@author: tc
'''

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import ListView, DetailView
from p4l.forms import RecordFilterForm
from p4l.models import Record
from p4l.utils import get_labels_for_uris
import json
import logging
from p4l.semantictree.forms.forms import SubjectForm
from django.utils.safestring import mark_safe


logger = logging.getLogger(__name__)

class RecordListView(ListView):
    
    queryset = Record.objects.select_related("language").prefetch_related('titles').distinct()  # @UndefinedVariable
    paginate_by = settings.NB_RECORDS_BY_PAGE
    template_name = "p4l/p4l_home.html"
    form_class = RecordFilterForm
    
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(RecordListView, self).dispatch(*args, **kwargs)
    
    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"
    
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(RecordDetailView, self).dispatch(*args, **kwargs)
    
    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)
        
        context['subjects_query_dict'] = json.dumps({
                            'data-url': settings.SPARQL_QUERY_ENDPOINT,
                            'data-query':  
"""
PREFIX skos:<http://www.w3.org/2004/02/skos/core#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl:<http://www.w3.org/2002/07/owl#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?uri ?label
WHERE {
    ?uri a skos:Concept.
    ?uri skos:inScheme <http://skos.um.es/unescothes/CS000> .
    ?uri skos:prefLabel ?label.
    FILTER (lang(?label) = ?language).
    ?uri skos:prefLabel ?lab.
    FILTER regex (str(?lab), ?reg, 'i').
    FILTER (lang (?lab) = ?language).
    BIND (STRLEN(STRBEFORE (str(?lab), ?reg)) AS ?place).
    BIND (STRLEN(STR(?lab)) AS ?len)
}
ORDER BY ?place ?len ?lab
""",
                            'data-root-query':
"""
PREFIX skos:<http://www.w3.org/2004/02/skos/core#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl:<http://www.w3.org/2002/07/owl#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?uri ?label
WHERE {
    ?uri a skos:Collection ;
    skos:inScheme <http://skos.um.es/unescothes/CS000> ;    
    rdfs:label ?label .
    FILTER (lang(?label) = ?language). 
    FILTER NOT EXISTS { [skos:member ?uri] }
}
""",
                            'data-childs-query':
"""
PREFIX skos:<http://www.w3.org/2004/02/skos/core#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl:<http://www.w3.org/2002/07/owl#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?uri ?label
WHERE {
  ?uri skos:inScheme <http://skos.um.es/unescothes/CS000> .
  { ?uri a ?type
    FILTER (?type = skos:Collection || ?type = skos:Concept) }.
  ?root skos:narrower|skos:member ?uri.
  ?uri skos:prefLabel|rdfs:label ?label.
  FILTER (lang(?label) = ?language).
}
""",
                            'data-child-count-query':
"""
PREFIX skos:<http://www.w3.org/2004/02/skos/core#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl:<http://www.w3.org/2002/07/owl#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>
SELECT (COUNT(?uri) as ?nb)
WHERE {
    ?uri skos:inScheme <http://skos.um.es/unescothes/CS000> .
    ?root skos:narrower|skos:member ?uri.
}
"""
                            })
        
        return context
        
        