# -*- 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
#
##############################################################################

"""
Formulaires configuration Exports Apogée (codes)
"""

from flask import flash, url_for, redirect, request, render_template
from flask_wtf import FlaskForm
from wtforms import SelectField, SubmitField

import app
from app.models import ScoDocSiteConfig


class ScoDocConfigurationForm(FlaskForm):
    "Panneau de configuration des logos"
    bonus_sport_func_name = SelectField(
        label="Fonction de calcul des bonus sport&culture",
        choices=[
            (name, displayed_name if name else "Aucune")
            for (name, displayed_name) in ScoDocSiteConfig.get_bonus_sport_class_list()
        ],
    )
    submit = SubmitField("Valider")
    cancel = SubmitField("Annuler", render_kw={"formnovalidate": True})


def configuration():
    "Page de configuration principale"
    # nb: le contrôle d'accès (SuperAdmin) doit être fait dans la vue
    form = ScoDocConfigurationForm(
        data={
            "bonus_sport_func_name": ScoDocSiteConfig.get_bonus_sport_class_name(),
        }
    )
    if request.method == "POST" and form.cancel.data:  # cancel button
        return redirect(url_for("scodoc.index"))
    if form.validate_on_submit():
        if (
            form.data["bonus_sport_func_name"]
            != ScoDocSiteConfig.get_bonus_sport_class_name()
        ):
            ScoDocSiteConfig.set_bonus_sport_class(form.data["bonus_sport_func_name"])
            app.clear_scodoc_cache()
            flash(f"Fonction bonus sport&culture configurée.")
        return redirect(url_for("scodoc.index"))

    return render_template(
        "configuration.html",
        form=form,
    )
