import logging

from django.core.management.base import BaseCommand

from intranet.search.core import sources, storages


log = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Purge old indexation artefacts'

    def add_arguments(self, parser):
        parser.add_argument('search', type=str)
        parser.add_argument('revision', nargs='?', type=int)

        parser.add_argument('--index', '-s', action='store', default='',
                            help='index name')
        parser.add_argument('--dry-run', '-d', action='store_true', default=False,
                            help='no act just print commands')
        parser.add_argument('--offset', '-o', action='store', type=int, default=10,
                            help='number of protected revisions')
        parser.add_argument('--noqueue', '-q', action='store_true', default=False,
                            help='don\'t add task to queue')

    def handle(self, search, revision=None, **options):
        revision_storage = storages.RevisionStorage()

        if revision:
            revisions = [revision_storage.get_by_id(revision)]
        else:
            revisions = revision_storage.get_for_purge(search, options['index'],
                                                       options['offset'])

        for revision in revisions:
            revision_options = options.copy()

            revision_options.update(revision=revision,
                                    priority=0)

            Source = sources.load(search, revision_options['index'])
            source = Source(revision_options)

            source.next('cleanup', purge=True)
