/* repo_view/stash.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 gettextrs::gettext;
use relm4::prelude::*;

use super::{RepoView, RepoViewMsg};
use crate::git;

impl RepoView {
    pub(super) fn handle_stash_message(
        &mut self,
        msg: RepoViewMsg,
        sender: &ComponentSender<RepoView>,
        root: &adw::ToastOverlay,
    ) {
        match msg {
            RepoViewMsg::Stash => {
                let p = self.path.clone();
                let msg = gettext("Changes stashed");
                sender.spawn_oneshot_command(move || {
                    RepoViewMsg::StashComplete(git::stash_push(&p, None, git::StashPushFlags::Default), msg)
                });
            }

            RepoViewMsg::StashWithUntracked => {
                let p = self.path.clone();
                let msg = gettext("Changes stashed");
                sender.spawn_oneshot_command(move || {
                    RepoViewMsg::StashComplete(git::stash_push(&p, None, git::StashPushFlags::IncludeUntracked), msg)
                });
            }

            RepoViewMsg::StashPop => {
                let p = self.path.clone();
                let msg = gettext("Stash popped");
                sender.spawn_oneshot_command(move || RepoViewMsg::StashComplete(git::stash_pop(&p, 0), msg));
            }

            RepoViewMsg::StashComplete(result, success_msg) => {
                match &result {
                    Ok(()) => root.add_toast(adw::Toast::new(&success_msg)),
                    Err(msg) => root.add_toast(adw::Toast::new(msg)),
                }

                if result.is_ok() {
                    sender.input(RepoViewMsg::Refresh);
                }
            }

            _ => unreachable!("handle_stash_message called with non-stash message"),
        }
    }
}
