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
#![cfg_attr(docsrs, feature(doc_cfg))]

use alloc::{boxed::Box, rc::Rc, vec::Vec};

use crate::{Context, ListenerData, Node, Signal};
use core::{
    any::{Any, TypeId},
    cell::{Ref, RefCell, RefMut},
    marker::PhantomData,
    
};


pub struct Handle<O> {
    node: Rc<RefCell<Node>>,
    _marker: PhantomData<O>,
}

impl<O> Handle<O> {
    pub fn new(object: O) -> Self
    where
        O: 'static,
    {
        Self {
            node: Rc::new(RefCell::new(Node {
                object: Box::new(object),
                listeners: Vec::new(),
            })),
            _marker: PhantomData,
        }
    }

    pub fn bind<O2, M>(
        &self,
        other: &Handle<O2>,
        mut listener: impl FnMut(&mut Context<O2>, M) + 'static,
    ) -> Listener
    where
        O: Signal<M>,
        O2: 'static,
        M: Clone + 'static,
    {
        let other = other.clone();
        self.listen::<M>(move |msg| {
            let mut cx = Context {
                handle: other.clone(),
                node: other.node.borrow_mut(),
            };
            listener(&mut cx, msg.clone());
        })
    }

    pub fn listen<M: 'static>(&self, mut listener: impl FnMut(&M) + 'static) -> Listener
    where
        O: Signal<M>,
    {
        let listener_id = listener.type_id();
        let listener = ListenerData {
            msg_id: TypeId::of::<M>(),
            listener_id: listener.type_id(),
            f: Box::new(move |msg| listener(msg.downcast_ref().unwrap())),
        };
        self.node.borrow_mut().listeners.push(listener);

        Listener {
            type_id: listener_id,
            node: self.node.clone(),
        }
    }

    pub fn unlisten<M: 'static>(&self, listener: impl FnMut(&M) + 'static) -> bool
    where
        O: Signal<M>,
    {
        let mut node = self.node.borrow_mut();
        if let Some(idx) = node
            .listeners
            .iter()
            .position(|listener_data| listener_data.listener_id == listener.type_id())
        {
            node.listeners.remove(idx);
            true
        } else {
            false
        }
    }

    pub fn cx(&self) -> Context<O> {
        Context {
            handle: self.clone(),
            node: self.node.borrow_mut(),
        }
    }

    pub fn borrow(&self) -> Ref<O>
    where
        O: 'static,
    {
        Ref::map(self.node.borrow(), |node| {
            node.object.downcast_ref().unwrap()
        })
    }

    pub fn borrow_mut(&self) -> RefMut<O>
    where
        O: 'static,
    {
        RefMut::map(self.node.borrow_mut(), |node| {
            node.object.downcast_mut().unwrap()
        })
    }
}

impl<O> Clone for Handle<O> {
    fn clone(&self) -> Self {
        Self {
            node: self.node.clone(),
            _marker: self._marker.clone(),
        }
    }
}

pub struct Listener {
    type_id: TypeId,
    node: Rc<RefCell<Node>>,
}

impl Listener {
    pub fn unlisten(&self) -> bool {
        let mut node = self.node.borrow_mut();
        if let Some(idx) = node
            .listeners
            .iter()
            .position(|listener| listener.listener_id == self.type_id)
        {
            node.listeners.remove(idx);
            true
        } else {
            false
        }
    }
}