/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>

This file is part of FitnessTrax.

FitnessTrax 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 3 of the
License, or (at your option) any later version.

FitnessTrax 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 FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
*/

use crate::{components::TextEntry, types::ParseError};
use gtk::prelude::*;

#[derive(Default)]
pub struct Steps {
    label: gtk::Label,
}

impl Steps {
    pub fn new(steps: Option<u32>) -> Self {
        let label = gtk::Label::builder()
            .css_classes(["card", "step-view"])
            .can_focus(true)
            .build();

        match steps {
            Some(s) => label.set_text(&format!("{}", s)),
            None => label.set_text("No steps recorded"),
        }

        Self { label }
    }

    pub fn widget(&self) -> gtk::Widget {
        self.label.clone().upcast()
    }
}

pub fn steps_editor<OnUpdate>(value: Option<u32>, on_update: OnUpdate) -> TextEntry<u32>
where
    OnUpdate: Fn(Option<u32>) + 'static,
{
    let text_entry = TextEntry::builder()
        .with_placeholder(   "0".to_owned())
        .with_renderer(|v| format!("{}", v))
        .with_parser(|v| v.parse::<u32>().map_err(|_| ParseError))
        .with_on_update(on_update);

    if let Some(time) = value {
        text_entry.with_value(time)
    } else {
        text_entry
    }.build()
}
