// Fragments - torrent_sorter.rs
// Copyright (C) 2022-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::RefCell;

use glib::subclass::prelude::*;
use glib::Properties;
use gtk::glib;
use gtk::prelude::*;
use gtk::subclass::filter::FilterImpl;
use transmission_gobject::{TrTorrent, TrTorrentStatus};

mod imp {
    use super::*;

    #[derive(Debug, Default, Properties)]
    #[properties(wrapper_type = super::FrgTorrentFilter)]
    pub struct FrgTorrentFilter {
        #[property(get, set = Self::set_status, builder(Default::default()))]
        status: RefCell<TrTorrentStatus>,
    }

    impl FrgTorrentFilter {
        pub fn set_status(&self, status: TrTorrentStatus) {
            *self.status.borrow_mut() = status;
            self.obj().changed(gtk::FilterChange::Different);
        }
    }

    #[glib::object_subclass]
    impl ObjectSubclass for FrgTorrentFilter {
        const NAME: &'static str = "FrgTorrentFilter";
        type Type = super::FrgTorrentFilter;
        type ParentType = gtk::Filter;
    }

    #[glib::derived_properties]
    impl ObjectImpl for FrgTorrentFilter {}

    impl FilterImpl for FrgTorrentFilter {
        fn match_(&self, item: &glib::Object) -> bool {
            let filter = self.obj();
            let torrent = item.downcast_ref::<TrTorrent>().unwrap();
            torrent.status() == filter.status()
        }
    }
}

glib::wrapper! {
    pub struct FrgTorrentFilter(ObjectSubclass<imp::FrgTorrentFilter>) @extends gtk::Filter;
}

impl FrgTorrentFilter {
    pub fn new() -> Self {
        Self::default()
    }
}

impl Default for FrgTorrentFilter {
    fn default() -> Self {
        glib::Object::new()
    }
}
