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

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

"""
Formulaire configuration Module Assiduités
"""

from flask_wtf import FlaskForm
from wtforms import SubmitField, DecimalField
from wtforms.fields.simple import StringField
from wtforms.widgets import TimeInput
import datetime


class TimeField(StringField):
    """HTML5 time input."""

    widget = TimeInput()

    def __init__(self, label=None, validators=None, fmt="%H:%M:%S", **kwargs):
        super(TimeField, self).__init__(label, validators, **kwargs)
        self.fmt = fmt
        self.data = None

    def _value(self):
        if self.raw_data:
            return " ".join(self.raw_data)
        if self.data and isinstance(self.data, str):
            self.data = datetime.time(*map(int, self.data.split(":")))
        return self.data and self.data.strftime(self.fmt) or ""

    def process_formdata(self, valuelist):
        if valuelist:
            time_str = " ".join(valuelist)
            try:
                components = time_str.split(":")
                hour = 0
                minutes = 0
                seconds = 0
                if len(components) in range(2, 4):
                    hour = int(components[0])
                    minutes = int(components[1])

                    if len(components) == 3:
                        seconds = int(components[2])
                else:
                    raise ValueError
                self.data = datetime.time(hour, minutes, seconds)
            except ValueError:
                self.data = None
                raise ValueError(self.gettext("Not a valid time string"))


class ConfigAssiduitesForm(FlaskForm):
    "Formulaire paramétrage Module Assiduités"

    morning_time = TimeField("Début de la journée")
    lunch_time = TimeField("Heure de midi (date pivot entre Matin et Après Midi)")
    afternoon_time = TimeField("Fin de la journée")

    tick_time = DecimalField("Granularité de la Time Line (temps en minutes)", places=0)

    submit = SubmitField("Valider")
    cancel = SubmitField("Annuler", render_kw={"formnovalidate": True})