1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/* model_activity.rs
 *
 * Copyright 2020-2021 Rasmus Thomsen <oss@cogitri.dev>
 *
 * 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 <http://www.gnu.org/licenses/>.
 */

use crate::{
    core::RefIter,
    plugins::{Plugin, PluginName},
};
use gtk::{
    gio::{self, prelude::*},
    glib::{self, subclass::prelude::*},
};
use std::{cell::Ref, convert::TryInto};

mod imp {
    use crate::plugins::{Plugin, PluginObject};
    use gtk::subclass::prelude::*;
    use gtk::{
        gio,
        glib::{self, Cast, StaticType},
    };
    use std::{
        cell::RefCell,
        convert::{TryFrom, TryInto},
    };

    #[derive(Debug, Default)]
    pub struct PluginList {
        pub vec: RefCell<Vec<Box<dyn Plugin>>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for PluginList {
        const NAME: &'static str = "HealthPluginList";
        type ParentType = glib::Object;
        type Type = super::PluginList;
        type Interfaces = (gio::ListModel,);
    }

    impl ObjectImpl for PluginList {}
    impl ListModelImpl for PluginList {
        fn item_type(&self) -> glib::Type {
            PluginObject::static_type()
        }

        fn n_items(&self) -> u32 {
            self.vec.borrow().len().try_into().unwrap()
        }

        fn item(&self, position: u32) -> Option<glib::Object> {
            self.vec
                .borrow()
                .get(usize::try_from(position).unwrap())
                .map(|o| PluginObject::new(o.clone()).upcast())
        }
    }
}

glib::wrapper! {
    /// An implementation of [gio::ListModel] that stores [Plugin](crate::plugin::Plugin)s.
    pub struct PluginList(ObjectSubclass<imp::PluginList>) @implements gio::ListModel;
}

impl Default for PluginList {
    fn default() -> Self {
        Self::new(Vec::new())
    }
}

impl PluginList {
    pub fn contains(&self, plugin_name: PluginName) -> bool {
        self.imp()
            .vec
            .borrow()
            .iter()
            .any(|p| p.name() == plugin_name)
    }

    pub fn is_empty(&self) -> bool {
        self.imp().vec.borrow().is_empty()
    }
    pub fn first(&self) -> Option<Box<dyn Plugin>> {
        self.imp().vec.borrow().first().cloned()
    }

    pub fn get(&self, index: usize) -> Option<Box<dyn Plugin>> {
        self.imp().vec.borrow().get(index).cloned()
    }

    pub fn iter(&self) -> RefIter<Box<dyn Plugin>> {
        RefIter::new(Ref::map(self.imp().vec.borrow(), |v| &v[..]))
    }

    pub fn last(&self) -> Option<Box<dyn Plugin>> {
        self.imp().vec.borrow().last().cloned()
    }

    pub fn len(&self) -> usize {
        self.imp().vec.borrow().len()
    }

    pub fn new(plugin_list: Vec<Box<dyn Plugin>>) -> Self {
        let o: Self = glib::Object::new();
        o.imp().vec.replace(plugin_list);
        o
    }

    pub fn push(&self, plugin: Box<dyn Plugin>) {
        let len = {
            let mut vec = self.imp().vec.borrow_mut();
            vec.push(plugin);
            vec.len() - 1
        };
        self.items_changed(len.try_into().unwrap(), 0, 1);
    }

    pub fn remove(&self, plugin_name: PluginName) -> Option<Box<dyn Plugin>> {
        let mut changed_position: Option<usize> = None;
        let mut ret: Option<Box<dyn Plugin>> = None;

        {
            let mut vec = self.imp().vec.borrow_mut();
            if let Some(f) = vec.iter().position(|x| x.name() == plugin_name) {
                ret = Some(vec.remove(f));
                changed_position = Some(f);
            }
        }
        if let Some(pos) = changed_position {
            self.items_changed(pos.try_into().unwrap(), 1, 0);
        }

        ret
    }
}

#[cfg(test)]
mod test {
    use super::PluginList;
    use crate::plugins::{Plugin, PluginName, StepsPlugin};

    #[test]
    fn new() {
        PluginList::new(Vec::new());
    }

    #[test]
    fn remove() {
        let list = PluginList::new(Vec::new());
        assert!(list.is_empty());
        assert!(list.remove(PluginName::Steps).is_none());
        let plugin = Box::new(StepsPlugin::new());
        list.push(plugin.clone());
        assert!(!list.is_empty());
        assert!(list.contains(PluginName::Steps));
        assert_eq!(list.remove(plugin.name()).unwrap().name(), plugin.name());
        assert!(!list.contains(PluginName::Calories));
    }
}