""" This module holds the command to compute assessments scores for the ``assessments`` app. """

from django.core.management.base import BaseCommand

from mtp.apps.trainings.models import TrainingSession


class Command(BaseCommand):
    """Command to compute assessments scores."""

    help = "Compute trainee scores for all sessions. " \
           "Use --force option to recompute closed session scores too."

    def add_arguments(self, parser):
        """Add needed arguments with this command."""

        parser.add_argument(
            '--force',
            action='store_true',
            dest='force',
            default=False,
            help='Force the recomputing scores when the session is closed.'
        )

    def handle(self, *args, **options):
        """We compute the assessments scores for all users in assessing sessions."""

        # We search the assessing session to compute these scores
        assessing_sessions = TrainingSession.objects.get_assessing_sessions()
        sessions_count = assessing_sessions.count()

        # We iterate on each assessing session
        for index, session in enumerate(assessing_sessions):

            # We (re)compute assessments scores if the session is opened or the computing is forced
            if session.state != session.STATE_CHOICES.CLOSED or options['force']:
                self.stdout.write('Session %s/%s : %s' % (index + 1, sessions_count, session))

                # We catch all exceptions during compute session scores to allow to continue
                # to calculate scores from following session.
                try:
                    session.compute_assessment_scores(force_recompute=True)
                except Exception as error:  # pylint: disable=broad-except
                    self.stdout.write('Compute fails! %s' % error)

            else:
                self.stdout.write(
                    'Session %s/%s : %s is closed. '
                    'Use --force option to recompute it.' % (index + 1, sessions_count, session)
                )
