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

@author: ymh
'''
from django.conf import settings
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(settings.DBPEDIA_URI_TEMPLATE % ("resource",""))
        #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(u"^(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. Exemple = XIIIe_siècle
                    century = re.findall(u"(\w+)(e|ème)_siècle_?(av._J.-C.)?", dbptitle)
                    if century:
                        val = self.rom_to_int(century[0][0])
                        if century[0][2] == 'av._J.-C.':
                            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()
    
    def rom_to_int(self, string):
        # from http://codereview.stackexchange.com/questions/902/conversion-from-to-roman-numbers
        table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]
        result = 0
        for letter, value in table:
            while string.startswith(letter):
                result += value
                string = string[len(letter):]
        return result