# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from core.models import (Notice)
from core.utils import show_progress
from jocondelab.models import NoticeYears
from django.db import reset_queries, transaction
import re

class Command(BaseCommand):
    
    help = "Extract Years from MILL field"
    
    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(self, *args, **options):
        
        millcache = {}
        yearre = re.compile("\d+")
        rejectre = re.compile("\d-\d")
        beforre = re.compile("av(\.|ant)? JC|- ", re.I)
        splitre = re.compile("\s*[,;]\s*")
        
        writer = None
        
        def getyear(millesime):
            year = None
            if not rejectre.search(millesime):
                yearmatch = yearre.search(millesime)
                if yearmatch:
                    year = int(millesime[yearmatch.start():yearmatch.end()])
                    if beforre.search(millesime):
                        year = - year
                    if year > 2012:
                        year = None
            if year is None:
                millcache[millesime] = year
            return year
        
        transaction.enter_transaction_management()
        transaction.managed()
        
        qs = Notice.objects.exclude(mill=None).exclude(mill='')
        count = qs.count()
        for i, notice in enumerate(qs):
            millfield = notice.mill
            writer = show_progress(i+1, count, millfield, 50, writer)
            years = []
            if millfield:
                millesimes = splitre.split(millfield)
                years = [millcache[m] if m in millcache else getyear(m) for m in millesimes]
                years = [y for y in years if y is not None]
            if len(years):
                sy = min(years)
                ey = max(years)
                nyobj, created = NoticeYears.objects.get_or_create(notice=notice, defaults={'start_year':sy,'end_year':ey})
                if not created:
                    nyobj.start_year = sy
                    nyobj.end_year = ey
                    nyobj.save()
            
            if not ((i+1) % 50):
                transaction.commit()
                reset_queries()
                
        transaction.commit()
        reset_queries()
        transaction.leave_transaction_management()
        