# -*- coding: UTF-8 -*

"""Groups & partitions
"""
from typing import Any

from app import db
from app.models import SHORT_STR_LEN
from app.models import GROUPNAME_STR_LEN


class Partition(db.Model):
    """Partition: découpage d'une promotion en groupes"""

    __table_args__ = (db.UniqueConstraint("formsemestre_id", "partition_name"),)

    id = db.Column(db.Integer, primary_key=True)
    partition_id = db.synonym("id")
    formsemestre_id = db.Column(
        db.Integer,
        db.ForeignKey("notes_formsemestre.id"),
        index=True,
    )
    # "TD", "TP", ... (NULL for 'all')
    partition_name = db.Column(db.String(SHORT_STR_LEN))
    # numero = ordre de presentation)
    numero = db.Column(db.Integer)
    # Calculer le rang ?
    bul_show_rank = db.Column(
        db.Boolean(), nullable=False, default=False, server_default="false"
    )
    # Montrer quand on indique les groupes de l'étudiant ?
    show_in_lists = db.Column(
        db.Boolean(), nullable=False, default=True, server_default="true"
    )
    groups = db.relationship(
        "GroupDescr",
        backref=db.backref("partition", lazy=True),
        lazy="dynamic",
    )

    def __init__(self, **kwargs):
        super(Partition, self).__init__(**kwargs)
        if self.numero is None:
            # génère numero à la création
            last_partition = Partition.query.order_by(Partition.numero.desc()).first()
            if last_partition:
                self.numero = last_partition.numero + 1
            else:
                self.numero = 1

    def __repr__(self):
        return f"""<{self.__class__.__name__} {self.id} "{self.partition_name or '(default)'}">"""

    def to_dict(self, with_groups=False) -> dict:
        """as a dict, with or without groups"""
        d = {
            "id": self.id,
            "formsemestre_id": self.partition_id,
            "name": self.partition_name,
            "numero": self.numero,
        }
        if with_groups:
            d["groups"] = [group.to_dict(with_partition=False) for group in self.groups]
        return d


class GroupDescr(db.Model):
    """Description d'un groupe d'une partition"""

    __tablename__ = "group_descr"
    __table_args__ = (db.UniqueConstraint("partition_id", "group_name"),)

    id = db.Column(db.Integer, primary_key=True)
    group_id = db.synonym("id")
    partition_id = db.Column(db.Integer, db.ForeignKey("partition.id"))
    #  "A", "C2", ...  (NULL for 'all'):
    group_name = db.Column(db.String(GROUPNAME_STR_LEN))

    etuds = db.relationship(
        "Identite",
        secondary="group_membership",
        lazy="dynamic",
    )

    def __repr__(self):
        return (
            f"""<{self.__class__.__name__} {self.id} "{self.group_name or '(tous)'}">"""
        )

    def get_nom_with_part(self) -> str:
        "Nom avec partition: 'TD A'"
        return f"{self.partition.partition_name or ''} {self.group_name or '-'}"

    def to_dict(self, with_partition=True) -> dict:
        """as a dict, with or without partition"""
        d = {
            "id": self.id,
            "partition_id": self.partition_id,
            "name": self.group_name,
        }
        if with_partition:
            d["partition"] = self.partition.to_dict(with_groups=False)
        return d


group_membership = db.Table(
    "group_membership",
    db.Column("etudid", db.Integer, db.ForeignKey("identite.id")),
    db.Column("group_id", db.Integer, db.ForeignKey("group_descr.id")),
    db.UniqueConstraint("etudid", "group_id"),
)
# class GroupMembership(db.Model):
#     """Association groupe / étudiant"""

#     __tablename__ = "group_membership"
#     __table_args__ = (db.UniqueConstraint("etudid", "group_id"),)
#     id = db.Column(db.Integer, primary_key=True)
#     etudid = db.Column(db.Integer, db.ForeignKey("identite.id"))
#     group_id = db.Column(db.Integer, db.ForeignKey("group_descr.id"))