""" This module holds the models of the ``metaplans`` app. """

from django.conf import settings
from django.db import models
from django.utils.text import Truncator
from django.utils.translation import ugettext_lazy as _

from mtp.apps.common.models import Orderable
from mtp.apps.sync.models import Syncable

from .managers import (
    MetaplanPropositionManager, MetaplanPropositionQuerySet,
    MetaplanManager, MetaplanQuerySet
)


class Metaplan(Orderable, Syncable):
    """ A Metaplan allows to organize propositions on a work subject and
    assign them a color in a way similar to Post-It notes.

    Attributes
    ----------
    name : django ``CharField``
        The name of the metaplan, mandatory.
    session : foreign key to ``mtp.apps.trainings.TrainingSession``

    Notes
    -----
    This model is ``Syncable``.
    """

    name = models.CharField(_("name"), max_length=100)
    session = models.ForeignKey(
        'trainings.TrainingSession',
        related_name='metaplans',
        on_delete=models.CASCADE
    )

    objects = MetaplanManager.from_queryset(MetaplanQuerySet)()

    def __str__(self):
        return self.name

    def get_propositions(self):
        """
        Returns
        -------
        list
            Return all propositions of metaplan.

        """
        return self.propositions.non_deleted()

    def get_grouped_propositions(self):
        """
        Returns
        -------
        dict
            Return all propositions organized by group.

        """

        propositions_grouped = {}
        for proposition in self.propositions.filter(is_deleted=False):
            prop_group = proposition.group
            if prop_group in propositions_grouped:
                propositions_grouped[prop_group].append(proposition)
            else:
                propositions_grouped[prop_group] = [proposition]
        return propositions_grouped


class MetaplanProposition(Syncable):
    """ A Metaplan Proposition

    Attributes
    ----------
    metaplan : foreign key to ``mtp.apps.metaplans.Metaplan``
    group : django ``PositiveIntegerField``
        Group of the proposition.
        The iOS client app currently uses integers from 0 to 3
        to distinguish groups.
    user : django ``ForeignKey``
        The user who entered this proposition.
    text : django ``CharField``
        The text of the proposition.

    Notes
    -----
    This model is ``Syncable``.

    """
    metaplan = models.ForeignKey(
        'metaplans.Metaplan',
        related_name='propositions',
        on_delete=models.CASCADE
    )
    group = models.PositiveIntegerField(_("group"), default=0)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name=_("user"),
        on_delete=models.CASCADE
    )
    text = models.CharField(_("text"), max_length=100)

    objects = MetaplanPropositionManager.from_queryset(MetaplanPropositionQuerySet)()
