import argparse

from django.core.management.base import BaseCommand

from intranet.femida.src.interviews.models import Interview
from intranet.femida.src.interviews.workflow import InterviewWorkflow
from intranet.femida.src.users.models import get_robot_femida


class Command(BaseCommand):

    help = 'Cancel interviews'

    def add_arguments(self, parser):
        parser.add_argument(
            '-f',
            '--file',
            action='store',
            type=argparse.FileType(),
            help='Path to a file or files with ids separated with a space',
        )
        parser.add_argument(
            '--ids',
            nargs='*',
            help='List of interview ids separated with a space',
        )
        parser.add_argument('--dry-run', action='store_true')
        parser.add_argument(
            '--cancel-reason',
            '-c',
            action='store',
            required=False,
            type=str,
            default='Cancel old interviews',
            help='Reason for canceling interviews',
        )

    def handle(self, *args, **options):
        ids = options['ids']
        if options['file']:
            ids = self._read_file(options['file'])

        cancel_reason = options['cancel_reason']
        robot = get_robot_femida()
        canceled_interview_ids = []

        for interview in Interview.unsafe.filter(id__in=ids):
            try:
                if not options['dry_run']:
                    wf = InterviewWorkflow(interview, robot)
                    wf.perform_action('cancel', strict=False, cancel_reason=cancel_reason)
            except Exception as exc:
                self.stdout.write(
                    self.style.ERROR(
                        f'Could not cancel interview {interview.id} because of:\n{exc}',
                    ),
                )
            else:
                canceled_interview_ids.append(interview.id)

        self.stdout.write(
            self.style.SUCCESS(
                f'Successfully canceled {len(canceled_interview_ids)} '
                f'interview(s)\n{canceled_interview_ids}'
            ),
        )

    def _read_file(self, file):
        """Extracts interview's ids from a file."""
        file_content = file.read().strip()

        if len(file_content) == 0:
            raise ValueError('File is empty')
        return list(
            map(
                lambda id_string: id_string.strip(),
                file_content.split(' '),
            )
        )
