// Fragments - folder_page_contents.rs
// Copyright (C) 2023  Felix Häcker <haeckerfelix@gnome.org>
//
// 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 <https://www.gnu.org/licenses/>.

use std::cell::OnceCell;

use adw::prelude::*;
use adw::subclass::prelude::*;
use gio::SimpleAction;
use glib::{clone, subclass, Properties};
use gtk::{gio, glib, CompositeTemplate};
use transmission_gobject::TrFile;

use crate::model::{FrgFileFilter, FrgFileSorter};

mod imp {
    use super::*;

    #[derive(Debug, Default, Properties, CompositeTemplate)]
    #[template(resource = "/de/haeckerfelix/Fragments/gtk/folder_page_contents.ui")]
    #[properties(wrapper_type = super::FrgFolderPageContents)]
    pub struct FrgFolderPageContents {
        #[property(get, set, construct_only)]
        file: OnceCell<TrFile>,
        #[property(get, set, construct_only)]
        sorter: OnceCell<FrgFileSorter>,
        #[property(get = Self::scroll_pos, set, construct_only, type = f64)]
        scroll_pos: OnceCell<f64>,

        #[template_child]
        scrolled_window: TemplateChild<gtk::ScrolledWindow>,
        #[template_child]
        searchbar: TemplateChild<gtk::SearchBar>,
        #[template_child]
        searchentry: TemplateChild<gtk::SearchEntry>,
        #[template_child]
        listview: TemplateChild<gtk::ListView>,
        #[template_child]
        filter: TemplateChild<FrgFileFilter>,
        #[template_child]
        sort_model: TemplateChild<gtk::SortListModel>,

        view_actions: gio::SimpleActionGroup,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for FrgFolderPageContents {
        const NAME: &'static str = "FrgFolderPageContents";
        type ParentType = adw::Bin;
        type Type = super::FrgFolderPageContents;

        fn class_init(klass: &mut Self::Class) {
            klass.bind_template();
            klass.bind_template_callbacks();
        }

        fn instance_init(obj: &subclass::InitializingObject<Self>) {
            obj.init_template();
        }
    }

    #[glib::derived_properties]
    impl ObjectImpl for FrgFolderPageContents {
        fn constructed(&self) {
            self.parent_constructed();

            self.sort_model.set_sorter(Some(&self.obj().sorter()));
            self.sort_model
                .set_model(Some(&self.obj().file().related()));

            // Needed, since listview needs a moment to populate the list
            glib::idle_add_local_once(clone!(@weak self as this => move|| {
                this.scrolled_window.vadjustment().set_value(*this.scroll_pos.get().unwrap());
            }));

            // Search
            self.searchbar.connect_search_mode_enabled_notify(
                clone!(@weak self as this => move |sb| {
                    let file = this.obj().file();

                    let model: gio::ListModel = if sb.is_search_mode() {
                        this.filter.set_folder(Some(&file));
                        file.torrent().files().upcast()
                    } else {
                        this.filter.set_folder(None::<&TrFile>);
                        file.related().upcast()
                    };

                    this.sort_model.set_model(Some(&model));
                }),
            );
            self.searchentry
                .bind_property("text", &self.filter.get(), "search")
                .build();

            // Those actions are page specific, unlike those which are defined in
            // FrgTorrentDialog
            self.obj()
                .insert_action_group("view", Some(&self.view_actions));
            let mut action;

            // view.select-all
            action = SimpleAction::new("select-all", None);
            action.connect_activate(clone!(@weak self as this => move |_, _| {
                this.obj().file().set_wanted(true);
            }));
            self.view_actions.add_action(&action);

            // view.deselect-all
            action = SimpleAction::new("deselect-all", None);
            action.connect_activate(clone!(@weak self as this => move |_, _| {
                this.obj().file().set_wanted(false);
            }));
            self.view_actions.add_action(&action);
        }
    }

    impl WidgetImpl for FrgFolderPageContents {}

    impl BinImpl for FrgFolderPageContents {}

    #[gtk::template_callbacks]
    impl FrgFolderPageContents {
        fn scroll_pos(&self) -> f64 {
            self.scrolled_window.vadjustment().value()
        }

        #[template_callback]
        fn row_activated(&self, pos: u32) {
            let model = self.listview.model().unwrap();
            let file = model.item(pos).unwrap().downcast::<TrFile>().unwrap();

            if file.is_folder() {
                self.obj()
                    .activate_action("view.show-folder", (&file.name().to_variant()).into())
                    .unwrap();
            } else {
                self.obj()
                    .activate_action("view.show-file", (&file.name().to_variant()).into())
                    .unwrap();
            }
        }
    }
}

glib::wrapper! {
    pub struct FrgFolderPageContents(ObjectSubclass<imp::FrgFolderPageContents>)
        @extends gtk::Widget, adw::Bin;
}

impl FrgFolderPageContents {
    pub fn new(file: &TrFile, sorter: &FrgFileSorter, scroll_pos: f64) -> Self {
        glib::Object::builder()
            .property("file", file)
            .property("sorter", sorter)
            .property("scroll-pos", scroll_pos)
            .build()
    }
}
