/* Progressable.vala
 *
 * Copyright 2019 Paulo Queiroz <pvaqueiroz@gmail.com>
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

/**
 * Progressable is a {@link Gtk.Overlay} that allows you to quickly toggle an
 * overlayed {@link Gtk.ProgressBar} on top of it's content. Useful when you run
 * async operations and need to let the user know something is being done in the
 * background.
 */
public class Marble.Progressable : Gtk.Overlay
{
    /**
     * Whether or not the widget is working. ``False`` by default.
     */
    public bool            loading      { get; set; default = false; }

    public Gtk.ProgressBar progress_bar { get; construct set; }

    private const string   DEFAULT_STYLE = """
        .loadable > progressbar {
            background: alpha(darker(@theme_bg_color), .6);
        }
    """;

    /**
     * Creates a new {@link Marble.Progressable}.
     */
    public Progressable()
    {
        this.progress_bar = new Gtk.ProgressBar();
        this.progress_bar.set_pulse_step(0.5);

        this.add_overlay(this.progress_bar);
        this.set_overlay_pass_through(this.progress_bar, false);

        this.notify["loading"].connect(this.loading_changed);

        this.get_style_context().add_class("loadable");
        Marble.set_theming_for_data(this.progress_bar, DEFAULT_STYLE, null,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
    }

    private void loading_changed()
    {
        if (this.loading)
            this.progress_bar.show();
        else
            this.progress_bar.hide();
    }

    /**
     * Make ``this.progress_bar`` start pulsating in an infinite loop.
     *
     * @return always return false
     */
    public bool pulse()
    {
        this.progress_bar.pulse();

        Timeout.add(1500, () => { return (this.pulse()); });

        return (false);
    }
}
