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

@author: rvelt
'''

from core.utils import show_progress
from django.conf import settings
from django.core.management.base import NoArgsCommand
from jocondelab.models import (DbpediaResource, DbpediaTranslation)
from django.db import transaction
import re
from SPARQLWrapper import SPARQLWrapper2
from optparse import make_option
import traceback

class Command(NoArgsCommand):
    
    help = "Import tag translations from dbpedia"
    
    option_list = NoArgsCommand.option_list + (
        make_option('--all',
            action='store_true',
            dest='all',
            default=False,
            help='force all dbpedia uris to be updated, not only those not yet processed'
        ),
    )
    
    def handle_noargs(self, **options):
        
        langstr = ','.join(['"%s"'%l[0] for l in settings.LANGUAGES])
        endpointre = re.compile('^http:\/\/\w+\.?dbpedia.org')
        
        qs = DbpediaResource.objects
        
        if not options.get('all', False):
            qs = qs.filter(translations=None)
        
        count = qs.count()
        
        qs = qs.extra(select={"notice_count": "SELECT SUM(nb_notice) FROM core_term WHERE core_term.dbpedia_uri = jocondelab_dbpediaresource.uri"}).order_by("-notice_count")
        
        writer = None
        
        for i,obj in enumerate(qs):
            writer = show_progress(i+1, count, obj.uri, 50, writer)
            
            try:
                with transaction.commit_on_success():
                    DbpediaTranslation.objects.filter(dbpediaresource=obj).delete()
                    endpointuri = settings.WIKIPEDIA_URLS[obj.lang]['dbpedia_sparql_url']
                    endpoint = SPARQLWrapper2(endpointuri)
                    sparql = """
                    select lang(?label) as ?lang, ?label where {
                        <%s> rdfs:label ?label .
                        FILTER (lang(?label) IN (%s))
                    }
                    """%(obj.uri, langstr)
                    endpoint.setQuery(sparql)
                    results = endpoint.query()
                    
                    for binding in results.bindings:
                        DbpediaTranslation.objects.create(
                            dbpediaresource = obj,
                            lang = binding[u"lang"].value,
                            label = binding[u"label"].value
                                                           )
            except Exception as e:
                print "\nError processing resource %s : %s" %(obj.uri,unicode(e))
                traceback.print_exception(type(e), e, sys.exc_info()[2])
                
        