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

@author: ymh
'''

from SPARQLWrapper import SPARQLWrapper2
from django.core.management.base import NoArgsCommand
from django.db import transaction, reset_queries
from jocondelab.models import Country
from core.models import Notice
from core.utils import show_progress
from django.utils.http import urlquote
from optparse import make_option


class Command(NoArgsCommand):

    help = "Import countries from dbpedia"
    
    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):
        
        def count_notices(uri):
            return Notice.objects.filter(noticeterm__term__dbpedia_uri=uri).count()
        
        def add_country(dbpedia_uri, iso_code_3, iso_code_2):
            nb_notices = count_notices(dbpedia_uri)
            countryobj, created = Country.objects.get_or_create(
                            dbpedia_uri = dbpedia_uri,
                            defaults = {
                                    'iso_code_3': iso_code_3,
                                    'iso_code_2': iso_code_2,
                                    'nb_notices': nb_notices
                                }
                            )
            if not created:
                countryobj.iso_code_3 = iso_code_3
                countryobj.iso_code_2 = iso_code_2
                countryobj.nb_notices = nb_notices
                countryobj.save()
        
        writer = None
        resource_prefix = u'http://fr.dbpedia.org/resource/'
        batch_size = options.get('batch_size', 50)
        
        transaction.enter_transaction_management()
        transaction.managed()

        endpoint = SPARQLWrapper2("http://fr.dbpedia.org/sparql")
        sparql = """
        select distinct ?pays ?code where {
                    ?pays rdf:type dbpedia-owl:Country .
                    ?pays prop-fr:iso ?code
                } LIMIT 300
        """
        endpoint.setQuery(sparql)
        results = endpoint.query()
        
        count = len(results.bindings)
        
        substitutions = [
                 (u'R%C3%A9publique_populaire_de_Chine', u'Chine')
                 ]
        
        for i,binding in enumerate(results.bindings):
            if binding[u"code"].type == 'literal':
                resource_suffix = urlquote(binding[u"pays"].value.replace(resource_prefix,""))
                for s in substitutions:
                    if resource_suffix == s[0]:
                        resource_suffix = s[1]
                        break
                dbpedia_uri = u'%s%s'%(resource_prefix, resource_suffix)
                writer = show_progress(i+1, count, dbpedia_uri, 50, writer)
                iso_codes = binding[u"code"].value.split(", ")
                if (len(iso_codes) > 1):
                    add_country(dbpedia_uri, iso_codes[0], iso_codes[1])

            if not ((i+1) % batch_size):
                transaction.commit()
                reset_queries()

        # insert code for Maurice and Antarctica
        extra_countries = [
                           (u'%sMaurice_(pays)'%resource_prefix, "MUS", "MU"),
                           (u'%sAntarctique'%resource_prefix, "ATA", "AQ")
                           ]
        for c in extra_countries:
            add_country(*c)
        
        transaction.commit()
        reset_queries()
        transaction.leave_transaction_management()
            