from django.core.management.base import BaseCommand

from mtp.apps.trainings.models import TrainingSession
from mtp.apps.trainings.redis_models import TrainingSession as RedisTrainingSession


class Command(BaseCommand):
    """Management command to update the training sessions stats.

    This commands will update the ``average_tablet_usage_time`` on the
    ``TrainingSession`` instances.
    """

    help = "Update sessions statistics"

    def handle(self, *args, **options):

        nb_sessions_to_update = 0
        nb_sessions_updated = 0

        # start by converting old entries
        RedisTrainingSession.convert_old_user_ids()

        # We get all the django ``TrainingSession`` instance who are
        # linked to a ``RedisTrainingSession`` instance and who are not
        # yet used for the stats (average_tablet_usage_time=None)
        sessions_to_update = TrainingSession.objects.filter(
            pk__in=RedisTrainingSession.collection(),
            average_tablet_usage_time=None
        )

        nb_sessions_to_update = sessions_to_update.count()
        self.stdout.write('%d session(s) to update' % nb_sessions_to_update)

        # We try to compute the stats for each session.
        for session in sessions_to_update:
            session.compute_average_tablet_usage_time()
            if session.average_tablet_usage_time is not None:
                nb_sessions_updated += 1

        self.stdout.write('%d successfully updated session(s)' % nb_sessions_updated)
