'''
Created on Jun 7, 2011

@author: ymh
'''

from django.core.management.base import NoArgsCommand
from django.core.management.color import no_style
from django.db import transaction
from hdabo.models import Datasheet
from hdabo.wp_utils import reorder_datasheet_tags
from hdabo.utils import show_progress
from optparse import make_option
import math
import sys


class Command(NoArgsCommand):
    '''
    Command to calculate the order of tags based on indexation
    recalculate all tags. Will ask for confirmation
    '''

    args = ''
    options = '-f : force '
    help = "calculate the order of tags based on indexation recalculate all tags. Will ask for confirmation"
    
    option_list = NoArgsCommand.option_list + (
        make_option('-f', '--force',
            action='store_true',
            dest='force',
            default=False,
            help='force reordering of all datasheets'),
        make_option('--noinput',
            action='store_true',
            dest='no_input',
            default=False,
            help='no input'),
        )


    def handle_noargs(self, **options):
        
        self.style = no_style()
        
        interactive = options.get('interactive', True) and not options.get('no_input', False)
        force = options.get('force', True)
        
        if interactive:
            confirm = raw_input("""You have requested to recalculate the index order of all the tags.
This will process all the tags in %s datasheets. Are you sure you want to do this ?
    Type 'yes' to continue, or 'no' to cancel: """ % ("all" if force else "not validated"))
        else:
            confirm = 'yes'
            
        if confirm != "yes":
            print "Tag reordering cancelled"
            return

        if force:
            queryset = Datasheet.objects.all()
        else:
            queryset = Datasheet.objects.filter(validated=False, manual_order=False)
        total = queryset.count()
        
        transaction.commit_unless_managed()
        transaction.enter_transaction_management()
        transaction.managed(True)

        try:
            for i, ds in enumerate(queryset):
                show_progress(i + 1, total, ds.title, 60)
                reorder_datasheet_tags(ds)
                transaction.commit()
        except:
            transaction.rollback()
            raise
        finally:
            transaction.leave_transaction_management()
            
        
