# -*- coding: utf-8 -*-
'''
Created on Sep 19, 2013

@author: rvelt
'''

from core.models import Term
from jocondelab.models import DbpediaFields
from django.core.management import BaseCommand
import csv
import os

class Command(BaseCommand):

    args = "csv_file"
    
    help = "Import csv file containing label translations missing from DbPedia"
    
    def handle(self, *args, **options):
        
        filepath = os.path.abspath(args[0])
        self.stdout.write("Importing %s" % filepath)
        
        with open(filepath,'rb') as csv_file:
            dialect = csv.Sniffer().sniff(csv_file.read(1024))
            csv_file.seek(0)
            reader = csv.DictReader(csv_file, dialect=dialect)
            for i,row in enumerate(reader):
                print row
                if row.get('language_code', None) and row.get('dbpedia_uri', None) and row.get('label', None):
                    qs = DbpediaFields.objects.filter(
                                                      language_code = row['language_code'],
                                                      dbpedia_uri = row['dbpedia_uri']
                                                      )
                    for f in qs:
                        f.label = row['label']
                        f.save()