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

@author: ymh
'''

from core.models import Term, Thesaurus
from core.rdf_models import graph
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 tree. The terms should have been already imported."
    
    option_list = NoArgsCommand.option_list + (
        make_option('-b', '--batch-size',
            dest= 'batch_size',
            type='int',
            default= 500,
            help= 'number of object to import in bulk operations' 
        ),                                               
    )

    
    def handle_noargs(self, **options):
        
        transaction.enter_transaction_management()
        transaction.managed()

        
        for thes in Thesaurus.objects.all():
            context = graph.get_context(URIRef(thes.uri))
            with Term.objects.disable_mptt_updates():  # @UndefinedVariable
                for i,(s,_,o) in enumerate(graph.triples((None, URIRef("http://www.w3.org/2004/02/skos/core#narrower"), None), context=context)):
                    print("%d - Thesaurus %s term pref label %s parent %s" % (i+1,thes.label, repr(o), repr(s)))
                    parent_term = Term.objects.get(uri=unicode(s))  # @UndefinedVariable
                    term = Term.objects.get(uri=unicode(o))  # @UndefinedVariable
                    term.tree_id = thes.id
                    term.parent = parent_term
                    term.save()

            Term.objects.filter(parent=None, thesaurus=thes).update(tree_id=thes.id)  # @UndefinedVariable
            
            print("Rebuilding tree %d" % thes.id)
            Term.objects.rebuild()  # @UndefinedVariable
            
            transaction.commit()
            reset_queries()
        

        transaction.leave_transaction_management()

            