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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
mod folders;

/// Definitions for UI controls for components
pub mod components;
/// Definition for event enumeration
pub mod events;
pub mod plugins;
pub mod core_module;

use std::collections::HashMap;
use std::hash::Hasher;
use std::sync::{Arc, RwLock, RwLockReadGuard};
use std::thread::spawn;

use crate::core::button::{Button};
use crate::modules::components::{ComponentDefinition, UIPathValue, UIValue};
use crate::modules::events::{SDCoreEvent, SDGlobalEvent};
use crate::modules::folders::FolderModule;

use serde::{Deserialize, Serialize};

use image::DynamicImage;
use crate::core::manager::CoreManager;
use crate::core::{check_feature_list_for_feature, CoreHandle, UniqueButton};
use crate::modules::core_module::CoreModule;
use crate::SocketManager;
use crate::util::{add_array_function, change_from_path, convert_value_to_path, remove_array_function, set_value_function};

/// Manages modules
#[derive(Default)]
pub struct ModuleManager {
    // Using a bunch of various maps to move performance cost to adding module, so getting info is as costless as possible

    module_map: RwLock<HashMap<String, UniqueSDModule>>,
    module_component_map: RwLock<HashMap<String, HashMap<String, ComponentDefinition>>>,
    component_map: RwLock<HashMap<String, (ComponentDefinition, UniqueSDModule)>>,
    component_listener_map: RwLock<HashMap<String, Vec<UniqueSDModule>>>,

    /// Separate list of modules that can render things
    rendering_modules: RwLock<HashMap<String, HashMap<String, UniqueSDModule>>>,
}

impl ModuleManager {
    /// Creates new module manager, used in daemon for loading plugins and base modules
    pub fn new() -> Arc<ModuleManager> {
        Arc::new(ModuleManager::default())
    }

    /// Adds a new module to be used with core
    pub fn add_module(&self, module: UniqueSDModule) {
        let module_name = module.name();

        // Adding to module map
        let mut module_map = self.module_map.write().unwrap();
        module_map.insert(module_name.clone(), module.clone());
        drop(module_map);

        // Adding to module component map
        let mut module_component_map = self.module_component_map.write().unwrap();
        for (component, definition) in module.components() {
            if let Some(component_map) = module_component_map.get_mut(&module_name) {
                component_map.insert(component, definition);
            } else {
                module_component_map.insert(module_name.clone(), {
                    let mut map = HashMap::new();
                    map.insert(component, definition);
                    map
                });
            }
        }
        drop(module_component_map);

        // Adding to component to module map
        let mut component_map = self.component_map.write().unwrap();
        for (component, definition) in module.components() {
            component_map.insert(component, (definition, module.clone()));
        }
        drop(component_map);

        // Adding to component listener map
        let mut component_listener_map = self.component_listener_map.write().unwrap();
        for listens_for in module.listening_for() {
            if let Some(array) = component_listener_map.get_mut(&listens_for) {
                array.push(module.clone());
            } else {
                component_listener_map.insert(listens_for, vec![module.clone()]);
            }
        }
        drop(component_listener_map);

        // Adding rendering modules to rendering map
        let mut rendering_modules = self.rendering_modules.write().unwrap();
        if check_feature_list_for_feature(&module.metadata().used_features, "rendering") {
            for component in module.listening_for() {
                if let Some(map) = rendering_modules.get_mut(&component) {
                    map.insert(module.name(), module.clone());
                } else {
                    rendering_modules.insert(component, {
                        let mut map = HashMap::new();

                        map.insert(module.name(), module.clone());

                        map
                    });
                }
            }
        }
        drop(rendering_modules);
    }

    /// Attempts to get module with specified name
    pub fn get_module(&self, name: &str) -> Option<UniqueSDModule> {
        self.get_modules().get(name).cloned()
    }

    /// Returns all modules in map format
    pub fn get_modules(&self) -> HashMap<String, UniqueSDModule> {
        self.module_map.read().unwrap().clone()
    }

    /// Returns all modules in vector format
    pub fn get_module_list(&self) -> Vec<UniqueSDModule> {
        self.module_map.read().unwrap().values().cloned().collect()
    }

    /// Returns modules from names provided if they exist
    pub fn get_modules_from_list(&self, list: &[String]) -> Vec<UniqueSDModule> {
        let module_map = self.get_modules();

        let mut modules = vec![];

        for item in list {
            if let Some(module) = module_map.get(item) {
                modules.push(module.clone())
            }
        }

        modules
    }

    /// Retrieves modules that are listening to a specified component
    pub fn get_modules_for_component(&self, component: &str) -> Vec<UniqueSDModule> {
        let handle = self.component_listener_map.read().unwrap();

        if let Some(modules) = handle.get(component) {
            modules.clone()
        } else {
            vec![]
        }
    }

    /// Retrieves modules that have added specified components
    pub fn get_modules_for_declared_components(&self, components: &[String]) -> Vec<UniqueSDModule> {
        let handle = self.component_map.read().unwrap();

        let mut shared_modules = vec![];

        for component in components {
            if let Some((_, module)) = handle.get(component) {
                shared_modules.push(module.clone());
            }
        }

        shared_modules.sort_by(|a, b| a.name().cmp(&b.name()));
        shared_modules.dedup_by(|a, b| a.name() == b.name());

        shared_modules
    }

    /// Retrieves modules that are listening to specified components
    pub fn get_modules_for_components(&self, components: &[String]) -> Vec<UniqueSDModule> {
        let handle = self.component_listener_map.read().unwrap();

        let mut shared_modules = vec![];

        for component in components {
            if let Some(modules) = handle.get(component) {
                shared_modules.extend(modules.clone());
            }
        }

        shared_modules.sort_by(|a, b| a.name().cmp(&b.name()));
        shared_modules.dedup_by(|a, b| a.name() == b.name());

        shared_modules
    }

    /// Retrieves components that module defined
    pub fn get_components_of_module(&self, module_name: &str) -> Option<HashMap<String, ComponentDefinition>> {
        let handle = self.module_map.read().unwrap();

        if let Some(module) = handle.get(module_name) {
            Some(module.components())
        } else {
            None
        }
    }

    /// Retrieves all components that all modules define
    pub fn get_components(&self) -> HashMap<String, (ComponentDefinition, UniqueSDModule)> {
        self.component_map.read().unwrap().clone()
    }

    /// Retrieves all components that all modules define, but in module to component map format
    pub fn get_module_component_map(&self) -> HashMap<String, HashMap<String, ComponentDefinition>> {
        self.module_component_map.read().unwrap().clone()
    }

    /// Retrieves all modules that can render things
    pub fn get_rendering_module_map(&self) -> HashMap<String, HashMap<String, UniqueSDModule>> {
        self.rendering_modules.read().unwrap().clone()
    }

    /// Retrieves all modules that should be able to render according to list of component names
    pub fn get_modules_for_rendering(&self, names: &Vec<String>) -> HashMap<String, UniqueSDModule> {
        let rendering_map = self.rendering_modules.read().unwrap();

        let mut map = HashMap::new();

        for name in names {
            if let Some(modules) = rendering_map.get(name) {
                map.extend(modules.clone())
            }
        }

        map
    }


    /// Retrieves component if it exists
    pub fn get_component(&self, component_name: &str) -> Option<(ComponentDefinition, UniqueSDModule)> {
        self.component_map.read().unwrap().get(component_name).cloned()
    }

    /// Returns module map read lock
    pub fn read_module_map(&self) -> RwLockReadGuard<HashMap<String, UniqueSDModule>> {
        self.module_map.read().unwrap()
    }

    /// Returns component map read lock
    pub fn read_component_map(&self) -> RwLockReadGuard<HashMap<String, (ComponentDefinition, UniqueSDModule)>> {
        self.component_map.read().unwrap()
    }

    /// Returns module component map read lock
    pub fn read_module_component_map(&self) -> RwLockReadGuard<HashMap<String, HashMap<String, ComponentDefinition>>> {
        self.module_component_map.read().unwrap()
    }

    /// Returns component listener map read lock
    pub fn read_component_listener_map(&self) -> RwLockReadGuard<HashMap<String, Vec<UniqueSDModule>>> {
        self.component_listener_map.read().unwrap()
    }

    /// Returns rendering modules map read lock
    pub fn read_rendering_modules_map(&self) -> RwLockReadGuard<HashMap<String, HashMap<String, UniqueSDModule>>> {
        self.rendering_modules.read().unwrap()
    }
}

/// Loads built-in modules into the module manager
pub fn load_base_modules(module_manager: Arc<ModuleManager>, socket_manager: Arc<SocketManager>) {
    module_manager.add_module(Arc::new(CoreModule { socket_manager }));
    module_manager.add_module(Arc::new(FolderModule::default()));
}

/// Reference counted module object
pub type UniqueSDModule = Arc<dyn SDModule>;

/// Module trait
#[allow(unused)]
pub trait SDModule: Send + Sync {
    // Module data
    /// Module name
    fn name(&self) -> String;

    // Components
    /// Definition for components that module will be providing
    fn components(&self) -> HashMap<String, ComponentDefinition>;

    /// Method for adding components onto buttons
    fn add_component(&self, core: CoreHandle, button: &mut Button, name: &str);

    /// Method for removing components from buttons
    fn remove_component(&self, core: CoreHandle, button: &mut Button, name: &str);

    /// Method for handling pasting components of plugin, can be used for any additional handling
    fn paste_component(&self, core: CoreHandle, reference_button: &Button, new_button: &mut Button);

    /// Method for letting core know what values component currently has
    fn component_values(&self, core: CoreHandle, button: &Button, name: &str) -> Vec<UIValue>;

    /// Method for setting values on components
    fn set_component_value(&self, core: CoreHandle, button: &mut Button, name: &str, value: Vec<UIValue>);

    /// Specifies which components the module will be receiving events for
    fn listening_for(&self) -> Vec<String>;

    /// Current settings state of the plugin
    fn settings(&self, core_manager: Arc<CoreManager>) -> Vec<UIValue> { vec![] }

    /// Method for updating plugin settings from UI
    fn set_setting(&self, core_manager: Arc<CoreManager>, value: Vec<UIValue>) { }

    /// Method for handling global events, add GLOBAL_EVENTS feature to the plugin metadata to receive global events
    fn global_event(&self, event: SDGlobalEvent) {}

    /// Method for handling core events, add CORE_EVENTS feature to the plugin metadata to receive core events
    fn event(&self, core: CoreHandle, event: SDCoreEvent) {}

    /// Method renderer will run for rendering additional information on a button if RENDERING feature was specified
    fn render(&self, core: CoreHandle, button: &UniqueButton, frame: &mut DynamicImage) {}

    /// Method for telling renderer if anything changed
    ///
    /// Changing state of the hash in anyway will cause renderer to either rerender, or use previous cache.
    /// This method will also called very frequently, so keep code in here fast
    fn render_hash(&self, core: CoreHandle, button: &UniqueButton, hash: &mut Box<dyn Hasher>) {}

    /// Metadata of the module, auto-implemented for plugins from plugin metadata
    fn metadata(&self) -> PluginMetadata {
        let mut meta = PluginMetadata::default();

        meta.name = self.name();

        meta
    }
}

/// Keeps relevant information about plugins
#[derive(Serialize, Deserialize, Clone)]
pub struct PluginMetadata {
    /// Name of the plugin
    pub name: String,
    /// Author of the plugin
    pub author: String,
    /// Description of the plugin
    pub description: String,
    /// Version of the plugin
    pub version: String,
    /// Used features of the plugin, used to determine if plugin is compatible with different software versions, see [crate::versions]
    pub used_features: Vec<(String, String)>
}

impl PluginMetadata {
    /// Lets you create plugin metadata without having to bother with creating strings for each property
    pub fn from_literals(name: &str, author: &str, description: &str, version: &str, used_features: &[(&str, &str)]) -> PluginMetadata {
        PluginMetadata {
            name: name.to_string(),
            author: author.to_string(),
            description: description.to_string(),
            version: version.to_string(),
            used_features: features_to_vec(used_features)
        }
    }
}

/// Retrieves module settings in array of UIPathValue
pub fn get_module_settings(core_manager: Arc<CoreManager>, module: &UniqueSDModule) -> Vec<UIPathValue> {
    module.settings(core_manager)
        .into_iter()
        .map(|x| convert_value_to_path(x, ""))
        .collect()
}

/// Adds new element into module setting's array
pub fn add_element_module_setting(core_manager: Arc<CoreManager>, module: &UniqueSDModule, path: &str) -> bool {
    let (changes, success) = change_from_path(path, module.settings(core_manager.clone()), &add_array_function(), false);

    if success {
        if !changes.is_empty() {
            module.set_setting(core_manager, changes);
            true
        } else {
            false
        }
    } else {
        false
    }
}

/// Removes an element from module setting's array
pub fn remove_element_module_setting(core_manager: Arc<CoreManager>, module: &UniqueSDModule, path: &str, index: usize) -> bool {
    let (changes, success) = change_from_path(path, module.settings(core_manager.clone()), &remove_array_function(index), false);

    if success {
        if !changes.is_empty() {
            module.set_setting(core_manager, changes);
            true
        } else {
            false
        }
    } else {
        false
    }
}

/// Sets value into module's setting
pub fn set_module_setting(core_manager: Arc<CoreManager>, module: &UniqueSDModule, value: UIPathValue) -> bool {
    let (changes, success) = change_from_path(&value.path, module.settings(core_manager.clone()), &set_value_function(value.clone()), false);

    if success {
        if !changes.is_empty() {
            module.set_setting(core_manager, changes);
            true
        } else {
            false
        }
    } else {
        false
    }
}

/// Sends global event to all modules, spawns a separate thread to do it, so doesn't block current thread
pub fn send_global_event_to_modules<T: Iterator<Item=UniqueSDModule> + Send + 'static>(event: SDGlobalEvent, modules: T) {
    spawn(move || {
        modules.for_each(|x| x.global_event(event.clone()));
    });
}

/// Converts features slice into Vec
pub fn features_to_vec(features: &[(&str, &str)]) -> Vec<(String, String)> {
    features.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect()
}

impl Default for PluginMetadata {
    fn default() -> Self {
        PluginMetadata::from_literals(
            "unspecified",
            "unspecified",
            "unspecified",
            "unspecified",
            &[]
        )
    }
}