from optparse import make_option

from django.core.management.base import BaseCommand, CommandError

from staff.oebs.tasks import RollupTask


class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option(
            '--dry',
            action='store_true',
            dest='dry',
            default=False,
            help="Only write logs, don't save data."
        ),
        make_option(
            '--force',
            action='store_true',
            dest='force',
            default=False,
            help="Rollup even if switch is disabled."
        ),
        make_option(
            '--nolock',
            action='store_true',
            dest='nolock',
            default=False,
            help='Do not use lock',
        ),
    )

    def handle(self, *args, **options):
        model_name = args[0] if args else None
        object_id = args[1] if len(args) > 1 else None
        dry = options.get('dry')
        force = options.get('force')

        params = {}
        if model_name:
            params['model'] = model_name
        if object_id:
            params['object_id'] = object_id
        if dry:
            params['dry'] = dry
        if force:
            params['force'] = force
        if options.get('nolock'):
            params.update(nolock=True)

        if model_name:
            RollupTask(**params)
        else:
            raise CommandError('Model is required (first argument)')
