from django.core.management.base import BaseCommand

from mtp.apps.surveys.models import Question


class Command(BaseCommand):
    """Management command to update surveys stats.

    Arguments
    ---------
    --force / -f : boolean, default to ``False``.
        If ``True``, all the answers for all the questions will be used to update the
        statistics. Useful if the algorithm about the statistics has changed.
        If ``False``, only answers that were not previously used to compute statistics are used.

    --verbosisity / -v : integer, default to 1
        If set to at least 0: no output
        If set to 1: a summary of the number of questions updated will be displayed when done
        If set to 2 and more: display work done for each question

    """

    help = "Update surveys statistics"

    def add_arguments(self, parser):
        parser.add_argument(
            '-f',
            '--force',
            action='store_true',
            help='Force to update statistics with all answers, not only new ones.'
        )

    def handle(self, *args, **options):
        force_all_answers = options['force']
        verbose = options['verbosity'] > 1

        nb_questions = 0
        nb_updated = 0
        nb_failed = 0

        queryset = Question.non_deleted.all()

        count = None
        if verbose:
            count = queryset.count()
            self.stdout.write('Will update %d questions:' % count)

        # Do the work for each question
        for index, question in enumerate(queryset):

            # Do the work for this question
            updated, failed = question.update_stats(force_all=force_all_answers)

            if verbose:
                self.stdout.write('  [%s/%d] Question %s: updated=%d, failed=%d' % (
                    str(index + 1).rjust(len(str(count))),  # Use the max count size to align items
                    count,
                    question.pk,
                    updated,
                    failed,
                ))
            if updated or failed:
                nb_updated += updated
                nb_failed += failed
                nb_questions += 1

        if verbose:
            self.stdout.write('\n')

        if options['verbosity']:  # display nothing if verbosity set to 0
            self.stdout.write(
                'Successfully updated statistics%s:\n'
                '  Updated questions: %d\n'
                '  Used answers: %d\n'
                '  Failed answers: %d' % (
                    ' (forced)' if force_all_answers else '',
                    nb_questions,
                    nb_updated,
                    nb_failed
                )
            )
