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

use super::{WorkingCopyView, WorkingCopyViewWidgets};

#[derive(Debug)]
pub enum FilterAction {
    Focus,
    Hide,
    Changed(String),
}

impl WorkingCopyView {
    pub(super) fn handle_filter_action(
        &mut self,
        action: FilterAction,
        widgets: &mut WorkingCopyViewWidgets,
        _sender: &ComponentSender<Self>,
    ) {
        match action {
            FilterAction::Focus => {
                widgets.search_bar.set_search_mode(true);
                widgets.filter_entry.grab_focus();
            }

            FilterAction::Hide => {
                widgets.filter_entry.set_text("");
                self.clear_filter_state();
            }

            FilterAction::Changed(query) => {
                if query == self.filter_query {
                    return;
                }

                let prior_selected = self.selected_paths_all();
                self.filter_query = query;
                self.repopulate_files_factory();
                self.reselect_files(&prior_selected);
            }
        }
    }

    pub(super) fn clear_filter_state(&mut self) {
        if self.filter_query.is_empty() {
            return;
        }

        let prior_selected = self.selected_paths_all();
        self.filter_query.clear();
        self.repopulate_files_factory();
        self.reselect_files(&prior_selected);
    }
}
