# -*- coding: utf-8 -*-
'''
Created on Jun 11, 2013

@author: ymh
'''

from core.models import Term, Thesaurus
from core.models.term import TermLabel
from core.rdf_models import graph
from core.wp_utils import normalize_term
from django.core.management.base import NoArgsCommand
from django.db import transaction, reset_queries
from optparse import make_option
from rdflib.term import URIRef


class Command(NoArgsCommand):

    help = "Import graph terms in relational database, to be run after import_skos"
    
    option_list = NoArgsCommand.option_list + (
        make_option('-b', '--batch-size',
            dest= 'batch_size',
            type='int',
            default= 50,
            help= 'number of object to import in bulk operations' 
        ),                                               
    )

    
    def handle_noargs(self, **options):
        
        batch_size = options.get('batch_size', 50)
        
        transaction.enter_transaction_management()
        transaction.managed()

                
        for thes in Thesaurus.objects.all():
            context = graph.get_context(URIRef(thes.uri))
            for i,(s,_,o) in enumerate(graph.triples((None, URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"), None), context=context)):
                self.stdout.write("%d - Thesaurus %s term pref label %s" % (i+1,thes.label, repr(o)))
                try:                
                    term = Term.objects.get(uri=unicode(s))  # @UndefinedVariable
                    lang = getattr(o, 'language', None)
                    pref_label = unicode(o).strip()
                    if term.label != pref_label:
                        term.label = pref_label
                        term.normalized_label = normalize_term(pref_label)
                        term.save()

                    if not TermLabel.objects.filter(label=pref_label, term=term, lang=lang).exists():
                        TermLabel.objects.create(label=pref_label, term=term, lang=lang)
                except Term.DoesNotExist:  # @UndefinedVariable
                    self.stdout.write("Thesaurus %s term pref label %s for %s does not exists" % (thes.label, repr(o), repr(s)))                
                if not ((i+1) % batch_size):
                    transaction.commit()
                    reset_queries()
            transaction.commit()
            reset_queries()
            
            for i,(s,_,o) in enumerate(graph.triples((None, URIRef("http://www.w3.org/2004/02/skos/core#altLabel"), None), context=context)):
                self.stdout.write("%d - Thesaurus %s term alt label %s for %s" % (i+1, thes.label, repr(o), repr(s)))
                try:
                    term = Term.objects.get(uri=unicode(s))  # @UndefinedVariable
                    alt_label = unicode(o).strip()
                    lang = getattr(o, 'language', None)
                    if not TermLabel.objects.filter(label=alt_label, term=term, lang=lang).exists():
                        TermLabel.objects.create(label=alt_label, term=term, lang=lang)
                except Term.DoesNotExist:  # @UndefinedVariable
                    self.stdout.write("Thesaurus %s term alt label %s for %s does not exists" % (thes.label, repr(o), repr(s)))
                if not ((i+1) % batch_size):
                    transaction.commit()
                    reset_queries()

            transaction.commit()
            reset_queries()
        transaction.leave_transaction_management()
            