# -*- 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 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):
        
        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()
        
        for i,binding in enumerate(results.bindings):
            if binding[u"code"].type == 'literal':
                dbpedia_uri = binding[u"pays"].value
                iso_codes = binding[u"code"].value.split(", ")
                Country.objects.create(
                    dbpedia_uri = dbpedia_uri,
                    iso_code_3 = iso_codes[0],
                    iso_code_2 = iso_codes[1])

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

        # insert code for Maurice
        Country.objects.create(dbpedia_uri=u'http://fr.dbpedia.org/resource/Maurice_(pays)', iso_code_3 = "MUS", iso_code_2 = "MU")
        
        transaction.commit()
        reset_queries()
        transaction.leave_transaction_management()
            