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
use std::rc::Rc;

use crate::{Storage, IdPath, Binding};

#[derive(Clone)]
pub struct State<T> {
    initial_value: T,
    storage: Option<Rc<Storage>>,
    key: Option<(IdPath, usize)>,
}

impl<T> State<T> where T: 'static + Clone {
    pub fn new(initial_value: impl Into<T>) -> Self {
        Self {
            initial_value: initial_value.into(),
            storage: None,
            key: None,
        }
    }

    pub fn link(&mut self, storage: Rc<Storage>, id_path: IdPath, i: usize) {
        let key = (id_path.clone(), i);

        self.storage = Some(storage.clone());
        self.key = Some(key.clone());

        if !storage.contains_state(&key) {
            storage.insert_state(key, self.initial_value.clone());
        }
    }

    pub fn get(&self) -> T {
        let storage = self.storage.as_ref().expect("Storage not linked prior to get");
        storage.state::<T>(self.key.as_ref().unwrap())
    }

    pub fn set(&self, value: T) {
        let storage = self.storage.as_ref().expect("Storage not linked prior to set");
        storage.insert_state(self.key.clone().unwrap(), value);
    }

    pub fn binding(&self) -> Binding<T> {
        let self1 = self.clone();
        let self2 = self.clone();
        Binding::new(
            move || self1.get(),
            move |value| self2.set(value),
        )
    }
}