/* confirm_dialog.rs
 *
 * Copyright 2026 Christian Kruse
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

use adw::prelude::*;
use gettextrs::gettext;
use relm4::prelude::*;

pub struct ConfirmDialogInit {
    pub heading: String,
    pub body: String,
    pub action_label: String,
    pub appearance: adw::ResponseAppearance,
    pub parent_window: Option<gtk::Window>,
}

#[derive(Debug)]
pub enum ConfirmDialogOutput {
    Confirmed,
    Cancelled,
}

pub struct ConfirmDialog;

#[relm4::component(pub)]
impl Component for ConfirmDialog {
    type Init = ConfirmDialogInit;
    type Input = ();
    type Output = ConfirmDialogOutput;
    type CommandOutput = ();

    view! {
        #[root]
        gtk::Box {}
    }

    fn init(init: Self::Init, root: Self::Root, sender: ComponentSender<Self>) -> ComponentParts<Self> {
        let dialog = adw::AlertDialog::builder()
            .heading(&init.heading)
            .body(&init.body)
            .build();

        dialog.add_response("cancel", &gettext("Cancel"));
        dialog.add_response("confirm", &init.action_label);
        dialog.set_response_appearance("confirm", init.appearance);
        dialog.set_default_response(Some("cancel"));
        dialog.set_close_response("cancel");

        dialog.connect_response(None, move |_dialog, response| {
            if response == "confirm" {
                sender.output(ConfirmDialogOutput::Confirmed).ok();
            } else {
                sender.output(ConfirmDialogOutput::Cancelled).ok();
            }
        });

        dialog.present(init.parent_window.as_ref());

        let widgets = view_output!();

        ComponentParts {
            model: ConfirmDialog,
            widgets,
        }
    }
}
