# -*- mode: python -*-
# -*- coding: utf-8 -*-

##############################################################################
#
# Gestion scolarite IUT
#
# Copyright (c) 1999 - 2024 Emmanuel Viennet.  All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   Emmanuel Viennet      emmanuel.viennet@viennet.net
#
##############################################################################

##############################################################################
#  Module "Avis de poursuite d'étude"
#  conçu et développé par Cléo Baras (IUT de Grenoble)
##############################################################################


"""ScoDoc : interface des fonctions de gestion des avis de poursuites d'étude

"""

from flask import flash, g, redirect, render_template, request, send_file, url_for

from app.decorators import permission_required, scodoc
from app.forms.pe.pe_sem_recap import ParametrageClasseurPE
from app.models import FormSemestre
from app.pe import pe_comp
from app.pe import pe_jury
from app.views import ScoData
from app.scodoc.sco_exceptions import ScoValueError
from app.scodoc.sco_permissions import Permission
import app.scodoc.sco_utils as scu

from app.views import notes_bp as bp


@bp.route("/pe_view_sem_recap/<int:formsemestre_id>", methods=("GET", "POST"))
@scodoc
@permission_required(Permission.ScoView)
def pe_view_sem_recap(formsemestre_id: int):
    """Génération des avis de poursuite d'étude"""

    formsemestre = FormSemestre.get_formsemestre(formsemestre_id)
    if not formsemestre.formation.is_apc():
        raise ScoValueError(
            """Le module de Poursuites d'Etudes
            n'est disponible que pour des formations BUT"""
        )

    if formsemestre.formation.get_cursus().NB_SEM < 6:
        raise ScoValueError(
            """Le module de Poursuites d'Etudes n'est pas prévu
            pour une formation de moins de 6 semestres"""
        )
    # L'année du diplome
    annee_diplome = pe_comp.get_annee_diplome_semestre(formsemestre)

    # Cosemestres diplomants
    cosemestres = pe_comp.get_cosemestres_diplomants(annee_diplome)

    form = ParametrageClasseurPE()

    cosemestres_tries = pe_comp.tri_semestres_par_rang(cosemestres)
    affichage_cosemestres_tries = {
        rang: ", ".join([sem.titre_annee() for sem in cosemestres_tries[rang]])
        for rang in cosemestres_tries
    }
    if request.method == "GET":
        return render_template(
            "pe/pe_view_sem_recap.j2",
            annee_diplome=annee_diplome,
            form=form,
            formsemestre=formsemestre,
            sco=ScoData(formsemestre=formsemestre),
            cosemestres=affichage_cosemestres_tries,
            rangs_tries=sorted(affichage_cosemestres_tries.keys()),
        )

    # request.method == "POST"
    if form.validate_on_submit():
        jury = pe_jury.JuryPE(annee_diplome, formsemestre_id, options=form.data)
        if not jury.diplomes_ids:
            flash("aucun étudiant à considérer !")
            return redirect(
                url_for(
                    "notes.pe_view_sem_recap",
                    scodoc_dept=g.scodoc_dept,
                    formsemestre_id=formsemestre_id,
                )
            )

        data = jury.get_zipped_data()

        return send_file(
            data,
            mimetype="application/zip",
            download_name=scu.sanitize_filename(jury.nom_export_zip + ".zip"),
            as_attachment=True,
        )

    return redirect(
        url_for(
            "notes.formsemestre_status",
            scodoc_dept=g.scodoc_dept,
            formsemestre_id=formsemestre_id,
        )
    )