"""This module holds the managers for the ``workshops`` app."""

from django.db import models
from django.db.models import Sum

from mtp.discrete_apps.versionable.managers import (
    PolymorphicManagerForDependency,
    PolymorphicQuerySetForDependency,
)

from mtp.apps.assessments.managers.activities import AssessableQuerySet
from mtp.apps.sync.managers import SyncableQuerySet


class DependencyWorkshopStepQuerySet(AssessableQuerySet, SyncableQuerySet, PolymorphicQuerySetForDependency):
    """QuerySet for the ``mtp.apps.workshops.models.WorkshopStep`` model"""

    def for_workshop(self, workshop):
        """Filter only steps steps who belongs to the given workshop.

        Parameters
        ----------
        workshop : mtp.apps.workshop.models.Workshop
            The workshop we want the steps from.

        Returns
        -------
        TrainingQueryset
            A clone of the original queryset (``self``), filtered.

        """

        return self.filter(workshop=workshop)


class DependencyWorkshopStepManager(PolymorphicManagerForDependency):
    """Manager for the ``mtp.apps.workshops.models.WorkshopStep`` model"""

    queryset_class = DependencyWorkshopStepQuerySet


class DependencyWorkshopStepQuestionQuerySet(AssessableQuerySet, SyncableQuerySet, PolymorphicQuerySetForDependency):
    """QuerySet for the ``mtp.apps.workshops.models.WorkshopStepQuestion`` model"""
    pass


class DependencyWorkshopStepQuestionManager(PolymorphicManagerForDependency):
    """Manager for the ``mtp.apps.workshops.models.WorkshopStep`` model"""

    queryset_class = DependencyWorkshopStepQuestionQuerySet


class WorkshopStepQuestionAnswerManager(models.Manager):
    """Manager for the ``mtp.apps.workshops.models.WorkshopStepQuestionAnswer`` model"""
    pass


class WorkshopStepQuestionAnswerQuerySet(SyncableQuerySet, models.QuerySet):
    """QuerySet for the ``mtp.apps.workshops.models.WorkshopStepQuestionAnswer`` model"""

    def aggregate_points(self):
        """Return the points sum of answers in the queryset.

        Returns
        -------
        int
            The points sum.

        """
        return self.aggregate(Sum('points'))['points__sum'] or 0


class WorkshopStepQuestionUserAnswerManager(models.Manager):
    """Manager for the ``mtp.apps.workshops.models.WorkshopStepQuestionUserAnswer`` model"""
    pass


class WorkshopStepQuestionUserAnswerQuerySet(SyncableQuerySet, models.QuerySet):
    """QuerySet for the ``mtp.apps.workshops.models.WorkshopStepQuestionUserAnswer`` model"""

    def aggregate_points(self):
        """Return the points sum of user answers in the queryset.

        Returns
        -------
        int
            The points sum.

        """
        return self.aggregate(Sum('answer__points'))['answer__points__sum'] or 0
