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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::cell::Cell;
use std::rc::Rc;

use crate::{DomId, JsJson, DropResource};
use crate::struct_mut::{VecMut, ValueMut, HashMapMut};

use crate::driver_module::api::ApiImport;
use super::StaticString;
use super::dom_suspense::DomSuspense;
use super::{dom_command::{DriverDomCommand, sort_commands}, api::CallbackId};

#[derive(PartialEq)]
enum StateInitiation {
    Waiting {
        counter: u32,
    },
    Ready,
}

impl StateInitiation {
    pub fn new() -> Self {
        StateInitiation::Waiting {
            counter: 0
        }
    }

    pub fn is_ready(&self) -> bool {
        &Self::Ready == self
    }

    pub fn up(&mut self) {
        if let Self::Waiting { counter } = self {
            *counter += 1;
        }
    }

    ///
    /// Returns true if we have gone to zero while decreasing
    ///
    pub fn down(&mut self) -> bool {
        let send_commands = if let Self::Waiting { counter } = self {
            *counter -= 1;
            *counter == 0
        } else {
            false
        };

        if send_commands {
            *self = Self::Ready;
        }

        send_commands
    }
}

struct Commands {
    state: ValueMut<StateInitiation>,
    api: ApiImport,
    commands: VecMut<DriverDomCommand>,
    // For testing/debuging purposes
    log_enabled: Cell<bool>,
    log_vec: VecMut<DriverDomCommand>,
}

impl Commands {
    pub fn new(api: &ApiImport) -> &'static Self {
        Box::leak(Box::new(Commands {
            state: ValueMut::new(StateInitiation::new()),
            api: api.clone(),
            commands: VecMut::new(),
            log_enabled: Cell::new(false),
            log_vec: VecMut::new(),
        }))
    }

    fn log_start(&self) {
        if self.log_enabled.replace(true) {
            println!("log_start: already started");
        }
    }

    fn log_take(&self) -> Vec<DriverDomCommand> {
        self.log_enabled.replace(false);
        self.log_vec.take()
    }

    fn add_command(&self, command: DriverDomCommand) {
        if self.log_enabled.get() {
            self.log_vec.push(command.clone());
        }

        self.commands.push(command);
    }

    fn flush_dom_changes_inner(&self) {
        let state = self.commands.take();

        if !state.is_empty() {
            let mut out = Vec::<JsJson>::new();

            let state = sort_commands(state);

            for command in state {
                out.push(command.into_string());
            }

            let out = JsJson::List(out);
            self.api.dom_bulk_update(out);
        }
    }

    fn flush_dom_changes(&self) {
        let is_ready = self.state.map(|state| state.is_ready());

        if is_ready {
            self.flush_dom_changes_inner();
        }
    }

    fn fetch_up(&self) {
        self.state.change(|state| {
            state.up();
        });
    }

    fn fetch_down(&self) {
        let send_commands = self.state.change(|state| {
            state.down()
        });

        if send_commands {
            self.flush_dom_changes_inner();
        }
    }
}

type Callback = Rc<dyn Fn(DomId) + 'static>;

pub struct DriverDom {
    commands: &'static Commands,
    _sub1: DropResource,
    _sub2: DropResource,
    node_parent_callback: Rc<HashMapMut<DomId, Callback>>,
    pub dom_suspense: &'static DomSuspense,
}

impl DriverDom {
    pub fn new(api: &ApiImport) -> &'static DriverDom {
        let commands = Commands::new(api);

        let sub1 = api.on_fetch_start.add({
            move |_| {
                commands.fetch_up();
            }
        });

        let sub2 = api.on_fetch_stop.add({
            move |_| {
                commands.fetch_down();
            }
        });

        Box::leak(Box::new(DriverDom {
            commands,
            _sub1: sub1,
            _sub2: sub2,
            node_parent_callback: Rc::new(HashMapMut::new()),
            dom_suspense: DomSuspense::new(),
        }))
    }

    pub fn create_node(&self, id: DomId, name: impl Into<StaticString>) {
        let name = name.into();

        if name.as_str() == "vertigo-suspense" {
            self.dom_suspense.set_node_suspense(id);
        }

        self.commands.add_command(DriverDomCommand::CreateNode { id, name });
    }

    pub fn create_text(&self, id: DomId, value: &str) {
        self.commands.add_command(DriverDomCommand::CreateText {
            id,
            value: value.into(),
        })
    }

    pub fn update_text(&self, id: DomId, value: &str) {
        self.commands.add_command(DriverDomCommand::UpdateText {
            id,
            value: value.into(),
        });
    }

    pub fn set_attr(&self, id: DomId, name: impl Into<StaticString>, value: &str) {
        let name = name.into();

        self.commands.add_command(DriverDomCommand::SetAttr {
            id,
            name,
            value: value.into(),
        });
    }

    pub fn remove_attr(&self, id: DomId, name: impl Into<StaticString>) {
        self.commands.add_command(DriverDomCommand::RemoveAttr {
            id,
            name: name.into(),
        });
    }

    pub fn remove_text(&self, id: DomId) {
        self.commands.add_command(DriverDomCommand::RemoveText { id });
        self.dom_suspense.remove(id);
    }

    pub fn remove_node(&self, id: DomId) {
        self.commands.add_command(DriverDomCommand::RemoveNode { id });
        self.dom_suspense.remove(id);
    }

    pub fn insert_before(&self, parent: DomId, child: DomId, ref_id: Option<DomId>) {
        self.commands.add_command(DriverDomCommand::InsertBefore { parent, child, ref_id });

        if let Some(callback) = self.node_parent_callback.get(&child) {
            callback(parent);
        }

        self.dom_suspense.set_parent(child, parent);
    }

    pub fn insert_css(&self, selector: &str, value: &str) {
        self.commands.add_command(DriverDomCommand::InsertCss {
            selector: selector.into(),
            value: value.into(),
        });
    }

    pub fn create_comment(&self, id: DomId, value: impl Into<String>) {
        self.commands.add_command(DriverDomCommand::CreateComment {
            id,
            value: value.into(),
        })
    }

    pub fn remove_comment(&self, id: DomId) {
        self.commands.add_command(DriverDomCommand::RemoveComment { id });
        self.dom_suspense.remove(id);
    }

    pub fn callback_add(&self, id: DomId, event_name: impl Into<String>, callback_id: CallbackId) {
        self.commands.add_command(DriverDomCommand::CallbackAdd {
            id,
            event_name: event_name.into(),
            callback_id
        });
    }

    pub fn callback_remove(&self, id: DomId, event_name: impl Into<String>, callback_id: CallbackId) {
        self.commands.add_command(DriverDomCommand::CallbackRemove {
            id,
            event_name: event_name.into(),
            callback_id
        });
    }

    pub fn log_start(&self) {
        self.commands.log_start();
    }

    pub fn log_take(&self) -> Vec<DriverDomCommand> {
        self.commands.log_take()
    }

    pub fn flush_dom_changes(&self) {
        self.commands.flush_dom_changes();
    }

    pub fn node_parent(&self, node_id: DomId, callback: impl Fn(DomId) + 'static) -> DropResource {
        self.node_parent_callback.insert(node_id, Rc::new(callback));

        let node_parent_callback = self.node_parent_callback.clone();

        DropResource::new(move || {
            node_parent_callback.remove(&node_id);
        })
    }
}