/* working_copy_view/rebase.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::gtk;
use relm4::prelude::*;

use super::{WorkingCopyView, WorkingCopyViewMsg, WorkingCopyViewOutput};
use crate::confirm_dialog::{ConfirmDialog, ConfirmDialogInit, ConfirmDialogOutput};

#[derive(Debug)]
pub enum RebaseAction {
    AbortClicked,
    ContinueClicked,
    AbortConfirmed,
}

impl WorkingCopyView {
    pub(super) fn handle_rebase_action(
        &mut self,
        action: RebaseAction,
        sender: &ComponentSender<Self>,
        root: &gtk::Box,
    ) {
        match action {
            RebaseAction::ContinueClicked => {
                sender.output(WorkingCopyViewOutput::RebaseContinue).ok();
            }

            RebaseAction::AbortClicked => {
                let window = root.ancestor(gtk::Window::static_type()).and_downcast::<gtk::Window>();

                self.confirm_dialog = Some(
                    ConfirmDialog::builder()
                        .launch(ConfirmDialogInit {
                            heading: gettext("Abort Rebase?"),
                            body: gettext(
                                "All rebased commits will be discarded and the branch will be reset to its previous \
                                 state.",
                            ),
                            action_label: gettext("Abort Rebase"),
                            appearance: adw::ResponseAppearance::Destructive,
                            parent_window: window,
                        })
                        .forward(sender.input_sender(), |output| match output {
                            ConfirmDialogOutput::Confirmed => WorkingCopyViewMsg::Rebase(RebaseAction::AbortConfirmed),
                            ConfirmDialogOutput::Cancelled => WorkingCopyViewMsg::ConfirmDialogDismissed,
                        }),
                );
            }

            RebaseAction::AbortConfirmed => {
                self.confirm_dialog = None;
                sender.output(WorkingCopyViewOutput::RebaseAbort).ok();
            }
        }
    }
}
