# -*- coding: utf-8 -*-
'''
Created on Jan 29, 2012

@author: ymh
'''
from django.core.management.base import NoArgsCommand
from django.core.management.color import no_style
from hdabo.utils import show_progress
import re
from hdabo.models import Tag
from hdalab.models import TagYears

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        self.style = no_style()

        qs = Tag.objects.filter(category__label="Datation")
        total = qs.count()
        dbptstart = len("http://dbpedia.org/resource/")
        
        writer = None
        
        for i,tag in enumerate(qs):
            writer = show_progress(i+1, total, tag.label, 50, writer)
            start = None
            end = None
            range = re.findall("^(Années )?(-?\d+)\-?(\d+)?( en France| au cinéma)?$", tag.label)
            # S'il s'agit d'une année ou d'un ensemble d'années
            if range:
                start = int(range[0][1])
                end = start
                if range[0][0]:
                    end = start + 10
                if range[0][2]:
                    end = int(range[0][2])
            else:
                if tag.dbpedia_uri:
                    dbptitle = tag.dbpedia_uri[dbptstart:]
                    # S'il s'agit d'un siècle, on se fie à l'URL DBpedia,
                    # car les siècles y sont en chiffres arabes.
                    century = re.findall("(\d+)(st|nd|rd|th)_century_?(BC)?", dbptitle)
                    if century:
                        val = int(century[0][0])
                        if century[0][2] == 'BC':
                            start = -100*val
                        else:
                            start = 1 + 100*(val-1)
                        end = start + 100
            
            if start != None and end != None:
                ty = TagYears.objects.create(tag=tag, start_year=start, end_year=end)
                ty.save()
