"""This module holds the ``close_outdated_sessions`` command"""

from datetime import timedelta

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

from mtp.apps.common.commands_utils import TimeDeltaType
from mtp.apps.trainings.models import TrainingSession

class Command(BaseCommand):
    """Management command to close the "outdated" training session

    Where "outdated" means the session got a ``end_date`` in the past,
    and a ``state`` to ``DURING``.
    """

    help = "Close outdated training sessions"

    def add_arguments(self, parser):
        """Parse the arguments of the command

        This command got two args:
        - "--delta-after" : Will be parsed as a timedelta
        - "--noinput" : ``True`` if NOT provided, else ``False``

        See also
        --------
        ``mtp.apps.common.commands_utils.TimeDeltaType``
        The command parser for a ``timedelta`` argument.

        """

        parser.add_argument('--delta-after',
            type=TimeDeltaType(),
            dest='delta_after',
            default=timedelta(),
            help='Time interval to add to the "end_date" of the sessions')
        parser.add_argument('--noinput',
            action='store_false', dest='interactive', default=True,
            help="Do NOT prompt the user for input of any kind.")

    def handle(self, *args, **options):
        """Handle the command"""

        if options['interactive']:
            # First, display the number of the potential closed sessions to the user,
            # and ask for his agreement
            potential_closed_sessions = TrainingSession.objects.close_outdated(
                delta_after=options['delta_after'],
                dry_run=True
            )

            message = ['\n']
            message.append(
                'You are about to close %d session(s), are you sure to do this ?\n\n' %
                len(potential_closed_sessions)
            )
            message.append("Type 'yes' to continue, or 'no' to cancel: ")

            # If we got an input different from "yes", cancel the command
            if not self.get_input(message) == 'yes':
                raise CommandError('Session closing cancelled.')

        # Close the sessions
        closed_sessions = TrainingSession.objects.close_outdated(
            delta_after=options['delta_after'],
        )

        self.stdout.write('%d session(s) successfully closed' % len(closed_sessions))

    def get_input(self, message):
        """Get the user keyboard input

        Parameters
        ----------
        message: list
            A list of message to display to the user prior to the input

        Returns
        -------
        str: the user text input

        Notes
        -----
        This method is only there to easily mock the user's input

        """
        return input(''.join(message))  # pylint: disable=bad-builtin



