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

@author: rvelt
'''

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

class Command(BaseCommand):

    args = "csv_file"
    
    help = "Import csv file containing dbpedia uris and years"
    
    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('start_year', None) is not None and row.get('end_year', None) is not None:
                    start_year = int(row['start_year'])
                    end_year = int(row['end_year'])
                    dbpedia_uri = row.get('dbpedia_uri',None)
                    term_label = row.get('term_label',None)
                    ts = None
                    if dbpedia_uri is not None:
                        ts = Term.objects.filter(dbpedia_uri = dbpedia_uri)
                    elif term_label is not None:
                        ts = Term.objects.filter(label = term_label)
                    if ts is not None:
                        for t in ts:
                            dyobj, created = DbpediaYears.objects.get_or_create(term=t, defaults={'start_year': start_year, 'end_year': end_year})
                            if not created:
                                dyobj.start_year = start_year
                                dyobj.end_year = end_year
                                dyobj.save()