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

##############################################################################
#
# ScoDoc
#
# Copyright (c) 1999 - 2022 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
#
##############################################################################

"""
PN / Edition des coefs

Emmanuel Viennet, 2021
"""

from flask import url_for
from flask import jsonify
from flask import current_app, g, request
from flask.templating import render_template
from flask_login import current_user
from werkzeug.utils import redirect

from config import Config

from app import db
from app import models
from app.auth.models import User

from app.comp import moy_ue
from app.decorators import scodoc, permission_required
from app.scodoc import sco_edit_formation
from app.views import notes_bp as bp

# ---------------

from app.scodoc import sco_utils as scu
from app.scodoc import notesdb as ndb
from app.scodoc import sco_formations
from app import log

from app.models import Formation, UniteEns, Module
from app.scodoc.sco_exceptions import (
    ScoValueError,
    ScoLockedFormError,
    ScoGenError,
    AccessDenied,
)
from app.scodoc import html_sco_header
from app.scodoc.sco_permissions import Permission


@bp.route("/table_modules_ue_coefs/<int:formation_id>")
@bp.route("/table_modules_ue_coefs/<int:formation_id>/<int:semestre_idx>")
@scodoc
@permission_required(Permission.ScoView)
def table_modules_ue_coefs(formation_id, semestre_idx=None):
    """Description JSON de la table des coefs modules/UE dans une formation"""
    _ = models.Formation.query.get_or_404(formation_id)  # check
    if semestre_idx == "":
        semestre_idx = None
    df, ues, modules = moy_ue.df_load_module_coefs(formation_id, semestre_idx)
    # Titre des modules, en ligne
    col_titres_mods = [
        {
            "x": 1,  # 1ere colonne
            "y": row,
            # "nbX": 1,
            # "nbY": 1,
            "style": "title_mod title_" + scu.ModuleType(mod.module_type).name,
            "data": mod.code,
            "title": mod.titre,
        }
        for (row, mod) in enumerate(modules, start=2)
    ]
    row_titres_ue = [
        {
            "x": col,
            "y": 1,  # 1ere ligne
            "style": "title_ue",
            "data": ue.acronyme,
            "title": ue.titre,
        }
        for (col, ue) in enumerate(ues, start=2)
    ]
    # Les champs de saisie
    cells = []
    for (row, mod) in enumerate(modules, start=2):
        style = "champs champs_" + scu.ModuleType(mod.module_type).name
        for (col, ue) in enumerate(ues, start=2):
            cells.append(
                {
                    "x": col,
                    "y": row,
                    "style": style,
                    "data": df[mod.id][ue.id] or "",
                    "editable": True,
                    "module_id": mod.id,
                    "ue_id": ue.id,
                }
            )
    return jsonify(col_titres_mods + row_titres_ue + cells)


@bp.route("/set_module_ue_coef", methods=["POST"])
@scodoc
@permission_required(Permission.ScoChangeFormation)
def set_module_ue_coef():
    """Set coef from module to UE"""
    try:
        module_id = int(request.form["module_id"])
    except ValueError:
        return scu.json_error("invalid module_id", 400)
    try:
        ue_id = int(request.form["ue_id"])
    except ValueError:
        return scu.json_error("invalid ue_id", 400)
    try:
        coef = float(request.form["coef"].replace(",", "."))
    except ValueError:
        return scu.json_error("invalid coef", 400)
    module = models.Module.query.get(module_id)
    if module is None:
        return scu.json_error(f"module not found ({module_id})", 404)
    ue = models.UniteEns.query.get(ue_id)
    if not ue:
        return scu.json_error(f"UE not found ({ue_id})", 404)
    module.set_ue_coef(ue, coef)
    db.session.commit()
    module.formation.invalidate_cached_sems()

    return scu.json_error("ok", success=True, status=201)


@bp.route("/edit_modules_ue_coefs")
@scodoc
@permission_required(Permission.ScoChangeFormation)
def edit_modules_ue_coefs():
    """Formulaire édition grille coefs EU/modules"""
    formation_id = int(request.args["formation_id"])
    semestre_idx = request.args.get("semestre_idx", "")
    if len(semestre_idx.strip()) > 0:
        semestre_idx = int(semestre_idx)
    else:
        semestre_idx = None
    formation = models.Formation.query.filter_by(
        formation_id=formation_id
    ).first_or_404()
    locked = sco_formations.formation_has_locked_sems(formation_id)
    if locked:
        lockicon = scu.icontag("lock32_img", title="verrouillé")
    else:
        lockicon = ""
    H = [
        html_sco_header.sco_header(
            cssstyles=["css/table_editor.css"],
            javascripts=[
                "js/table_editor.js",
            ],
            page_title=f"Coefs programme {formation.acronyme}",
        ),
        f"""<h2>Formation {formation.titre} ({formation.acronyme})
        [version {formation.version}] code {formation.formation_code}
        {lockicon}
        </h2>
        """,
        render_template(
            "pn/form_modules_ue_coefs.html",
            formation=formation,
            data_source=url_for(
                "notes.table_modules_ue_coefs",
                scodoc_dept=g.scodoc_dept,
                formation_id=formation_id,
                semestre_idx=semestre_idx,
            ),
            data_save=url_for(
                "notes.set_module_ue_coef",
                scodoc_dept=g.scodoc_dept,
            ),
            semestre_idx=semestre_idx,
            semestre_ids=range(1, formation.get_parcours().NB_SEM + 1),
        ),
        html_sco_header.sco_footer(),
    ]

    return "\n".join(H)