"""
Tableau de bord utilisateur

Emmanuel Viennet, 2023
"""


from flask import flash, redirect, render_template, url_for
from flask import g, request
from flask_login import login_required
from app.auth.models import User
from app.decorators import (
    scodoc,
    permission_required,
)
from app.models import Departement, FormSemestre
from app.scodoc.sco_permissions import Permission
from app.scodoc import sco_preferences
from app.views import scodoc_bp as bp
from app.views import ScoData


@bp.route("/ScoDoc/user_board/<string:user_name>")
@scodoc
@login_required
def user_board(user_name: str):
    """Tableau de bord utilisateur: liens vers ses objets"""
    user = User.query.filter_by(user_name=user_name).first_or_404()
    (
        formsemestres_by_dept,
        modimpls_by_formsemestre,
    ) = FormSemestre.get_user_formsemestres_annee_by_dept(user)
    depts = {
        dept_id: Departement.query.get(dept_id) for dept_id in formsemestres_by_dept
    }
    dept_names = {
        dept_id: sco_preferences.get_preference("DeptName", dept_id=dept_id)
        for dept_id in formsemestres_by_dept
    }
    dept_names_sorted = {
        dept_id: dept_name
        for (dept_id, dept_name) in sorted(dept_names.items(), key=lambda x: x[1])
    }
    # TODO: le calendrier avec ses enseignements
    return render_template(
        "user_board/user_board.j2",
        depts=depts,
        dept_names=dept_names_sorted,
        formsemestres_by_dept=formsemestres_by_dept,
        modimpls_by_formsemestre=modimpls_by_formsemestre,
        sco=ScoData(),
        title=f"{user.get_prenomnom()}: tableau de bord",
        user=user,
    )
