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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! The actual Music Library Component Implementation

use std::{
    cell::OnceCell,
    fs::rename,
    num::NonZeroUsize,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use termusiclib::config::{SharedTuiSettings, TuiOverlay, v2::server::ScanDepth};
use tuirealm::{
    Component, Event, MockComponent,
    command::{Cmd, CmdResult, Direction, Position},
    event::{Key, KeyEvent, KeyModifiers},
    props::{Alignment, BorderType, Borders, Style},
    ratatui::{buffer::Buffer, layout::Rect},
};
use tuirealm_orx_tree::{
    NodeRef,
    component::{TreeView, cmd},
    traversal::{Dfs, OverNode, Traverser},
    types::{NodeIdx, NodeValue, Tree},
    widget::{
        CHILD_INDICATOR_LENGTH, HighlightDrawBehavior, Indicator, OrIndicators, calc_area_for_value,
    },
};

use crate::ui::{
    components::orx_music_library::scanner::{library_scan, library_scan_cb, recvec_to_tree},
    model::{DownloadTracker, TxToMain, UserEvent},
    msg::{
        DeleteConfirmMsg, GSMsg, IsDir, LIMsg, LINodeReady, LINodeReadySub, LIReloadData,
        LIReloadPathData, LIReqNode, Msg, PLMsg, TEMsg, YSMsg,
    },
};

/// Data stored in a node in the [`NewMusicLibraryComponent`]'s tree.
#[derive(Debug)]
pub struct MusicLibData {
    /// The actual path of the node.
    path: PathBuf,
    // TODO: refactor bools to be bitflags to save on storage?
    /// Store whether that path is a dir to show indicators & use for prefetching
    is_dir: IsDir,
    /// Indicator if the we already send a request to fetch this directory
    is_loading: bool,
    /// Indicator that loading information about this (file EACCESS) or directory loading has failed.
    is_error: bool,
    /// The `path.file_name`'s string representation.
    ///
    /// Lazily evaluated from `path`, only when it becomes necessary.
    // TODO: evaluate if it would be more performant to only cache if `path.file_name().to_str_lossy()` returns `Cow::Owned`.
    as_str: OnceCell<String>,
}

impl MusicLibData {
    /// Create new data.
    pub fn new(path: PathBuf, is_dir: IsDir) -> Self {
        assert!(path.is_absolute());
        let cell = OnceCell::new();
        // Due to our expectation of the path not ending in `..`, we can assume
        // that there is always a file_name, EXCEPT on linux on the root ("/").
        // We *could* call `canonicalize` here again, but it is more likely the caller already has done that.
        if path.file_name().is_none() {
            let _ = cell.set("/".to_string());
        }

        Self {
            path,
            is_dir,
            is_loading: false,
            is_error: false,
            as_str: OnceCell::default(),
        }
    }
}

/// Indicator when for directories when we already issued a load for it (and not have gotten a response back yet).
///
/// It should look like "⟳".
const LOADING_SYMBOL: &str = "\u{27F3}";
/// Indicator for when directory loading had failed.
///
/// It should look like "✕" (Multiplication) chosen for being 1 draw width.
const ERROR_SYMBOL: &str = "\u{2715}";

impl NodeValue for MusicLibData {
    fn render(&self, buf: &mut Buffer, area: Rect, offset: usize, style: Style) {
        // Unwrap should never panic here as we already check the case of there not being a file_name on instance creation.
        // The *only* possible way to currently get this panic is when using the default instance (which shouldnt be used).
        let res = self
            .as_str
            .get_or_init(|| self.path.file_name().unwrap().to_string_lossy().to_string());

        NodeValue::render(res, buf, area, offset, style);
    }

    fn render_with_indicators(
        &self,
        buf: &mut Buffer,
        mut area: Rect,
        mut offset: usize,
        style: Style,
        _is_leaf: bool,
        is_opened: impl FnOnce() -> bool,
    ) {
        if self.is_error {
            // indicator error loading that directory / file
            Indicator::render(ERROR_SYMBOL, 2, &mut offset, &mut area, buf, Some(style));
        } else if !self.is_dir.is_dir() {
            // not a directory

            // indent leaf nodes by what is taken up on the parent by the indicators, otherwise children and the parent would have the same visible indent
            let leaf_indent = CHILD_INDICATOR_LENGTH;
            let indent_area = calc_area_for_value(&mut offset, &mut area, usize::from(leaf_indent));
            buf.set_style(indent_area, style);
        } else if !self.is_loading {
            // directory that is not loading
            OrIndicators::default().with_style(style).render(
                &mut offset,
                &mut area,
                buf,
                is_opened(),
            );
        } else {
            // directory that is loading
            Indicator::render(LOADING_SYMBOL, 2, &mut offset, &mut area, buf, Some(style));
        }

        self.render(buf, area, offset, style);
    }
}

const LOADING_TREE_TEXT: &str = "Loading...";

#[derive(Debug, MockComponent)]
pub struct OrxMusicLibraryComponent {
    component: TreeView<MusicLibData>,
    config: SharedTuiSettings,

    tx_to_main: TxToMain,
    download_tracker: DownloadTracker,
    /// The path of the last yanked node.
    yanked_path: Option<PathBuf>,
}

impl OrxMusicLibraryComponent {
    fn get_inner_comp(config: &TuiOverlay) -> TreeView<MusicLibData> {
        // TODO: this component should either remount or listen to style changes and apply them
        TreeView::<MusicLibData>::default()
            .background(config.settings.theme.library_background())
            .foreground(config.settings.theme.library_foreground())
            .border(
                Borders::default()
                    .color(config.settings.theme.library_border())
                    .modifiers(BorderType::Rounded),
            )
            .inactive_style(Style::new().bg(config.settings.theme.library_background()))
            .indent_size(2)
            .highlight_symbol_draw_width(2)
            .highlight_symbol_draw_behavior(HighlightDrawBehavior::Static)
            .scroll_step_horizontal(NonZeroUsize::new(2).unwrap())
            .title(" Library ", Alignment::Left)
            .highlight_color(config.settings.theme.library_highlight())
            .highlight_symbol(&config.settings.theme.style.library.highlight_symbol)
            .empty_tree_text(LOADING_TREE_TEXT)
    }

    /// Get a new empty instance, which shows "Loading..." while empty.
    pub fn new_loading(
        config: SharedTuiSettings,
        tx_to_main: TxToMain,
        download_tracker: DownloadTracker,
    ) -> Self {
        let component = {
            let config = config.read();

            Self::get_inner_comp(&config)
        };

        Self {
            component,
            config,
            yanked_path: None,
            download_tracker,
            tx_to_main,
        }
    }

    /// Create a new instance, with a tree already set.
    #[expect(unused)]
    pub fn new(
        tree: Tree<MusicLibData>,
        config: SharedTuiSettings,
        tx_to_main: TxToMain,
        download_tracker: DownloadTracker,
    ) -> Self {
        let mut this = Self::new_loading(config, tx_to_main, download_tracker);

        this.component = this.component.tree(tree);

        this
    }

    /// Trigger a load with a message to change the tree root to the given path.
    ///
    /// This will make the current tree root be the new focused node.
    ///
    /// This will send a [`LIMsg::TreeNodeReady`] and change the root to `path`.
    fn trigger_load_with_focus<P: Into<PathBuf>>(&self, scan_path: P, focus_node: Option<PathBuf>) {
        let path = scan_path.into();
        library_scan(
            self.download_tracker.clone(),
            path,
            ScanDepth::Limited(2),
            self.tx_to_main.clone(),
            focus_node.map(|v| v.to_string_lossy().to_string()),
        );
    }

    /// Trigger a load for the given path, with the given depth.
    ///
    /// This will send a [`LIMsg::TreeNodeReadySub`] and does not change the root, unless the
    /// given path *is* the root.
    fn trigger_subload_with_focus(
        &self,
        path: PathBuf,
        depth: ScanDepth,
        focus_node: Option<PathBuf>,
    ) {
        let tx = self.tx_to_main.clone();
        library_scan_cb(self.download_tracker.clone(), path, depth, move |vec| {
            let _ = tx.send(Msg::Library(LIMsg::TreeNodeReadySub(LINodeReadySub {
                vec,
                focus_node,
            })));
        });
    }

    /// Store the currently selected node as yanked (for pasting with [`Self::paste`]).
    fn yank(&mut self) {
        if let Some(path) = self.get_selected_path() {
            self.yanked_path = Some(path.to_path_buf());
        }
    }

    /// Paste the previously yanked node in the currently selected node if it is a directory, otherwise in its parent.
    fn paste(&mut self) -> Result<Option<LIMsg>> {
        // This should happen before "yanked_path.take" so that we dont take, if we cannot apply it.
        // And "get_selected_path" cannot be put before here as that uses a immutable self reference, but ".take" requires mutable.
        if self.component.get_current_selected_node().is_none() {
            return Ok(None);
        }
        let Some(old_path) = self.yanked_path.take() else {
            return Ok(None);
        };
        let Some(selected_node_path) = self.get_selected_path() else {
            return Ok(None);
        };

        let pold_filename = old_path.file_name().context("no file name found")?;
        let old_parent = old_path.parent().context("old path had no parent")?;
        let selected_parent = selected_node_path
            .parent()
            .context("No Parent for currently selected node")?;

        let new_path = if selected_node_path.is_dir() {
            selected_node_path.join(pold_filename)
        } else {
            selected_parent.join(pold_filename)
        };

        rename(&old_path, &new_path)?;

        if new_path.starts_with(old_parent) {
            // new path is contained within old path's parent directory
            self.handle_reload_at(LIReloadPathData {
                path: new_path,
                change_focus: true,
            });
            self.handle_reload_at(LIReloadPathData {
                path: old_path,
                change_focus: false,
            });
        } else if old_parent.starts_with(selected_parent) {
            self.handle_reload_at(LIReloadPathData {
                path: new_path,
                change_focus: true,
            });
            self.handle_reload_at(LIReloadPathData {
                path: old_path,
                change_focus: false,
            });
        } else {
            // new path is not contained within old path's parent directory, so need to load both
            self.handle_reload_at(LIReloadPathData {
                path: new_path,
                change_focus: true,
            });
            self.handle_reload_at(LIReloadPathData {
                path: old_parent.to_path_buf(),
                change_focus: false,
            });
        }

        Ok(Some(LIMsg::PlaylistRunDelete))
    }

    /// Get the current root node's path, if there is one.
    fn get_root_path(&self) -> Option<&Path> {
        self.component
            .get_tree()
            .get_root()
            .map(|v| v.data().path.as_path())
    }

    /// Get the current selected node's path, if there is one.
    fn get_selected_path(&self) -> Option<&Path> {
        self.component
            .get_current_selected_node()
            .map(|v| v.data().path.as_path())
    }

    /// Also known as going up in the tree
    fn handle_left_key(&mut self) -> Option<Msg> {
        let selected_node = self.component.get_current_selected_node()?;

        if !selected_node.data().is_dir.is_dir()
            || !self.component.get_state().is_opened(selected_node.idx())
        {
            // When the selected node is a file or a closed directory, move focus to upper directory
            self.perform(Cmd::Custom(
                tuirealm_orx_tree::component::cmd::SELECT_PARENT,
            ));
        } else {
            // Directory is selected, but still open, close it
            // "Direction::Left" closes the current node
            self.component.perform(Cmd::Move(Direction::Left));
        }

        Some(Msg::ForceRedraw)
    }

    /// Also known as going down the tree / adding file to playlist.
    ///
    /// If `from_load: true`, disabled any extra functionality.
    fn handle_right_key(&mut self, from_load: bool) -> Option<Msg> {
        let selected_node = self.component.get_current_selected_node()?;

        if selected_node.data().is_dir.is_dir() {
            if selected_node.num_children() > 0
                || selected_node.data().is_dir == IsDir::YesLoadedEmpty
            {
                // Current node has children loaded, just open it.

                // "Direction::Right" opens the current node
                self.perform(Cmd::Move(Direction::Right));

                Some(Msg::ForceRedraw)
            } else if !selected_node.data().is_loading {
                // Current node does not have any children and is not loading, trigger a load for it
                self.handle_reload_at(LIReloadPathData {
                    path: selected_node.data().path.clone(),
                    change_focus: true,
                });
                Some(Msg::ForceRedraw)
            } else {
                // Current node does not have any children and is loading, dont do anything
                None
            }
        } else if !from_load {
            // Node is a file, try to add it to the playlist; at least if we are not in a load
            Some(Msg::Playlist(PLMsg::Add(selected_node.data().path.clone())))
        } else {
            // we are in a load, so we dont want to handle files here
            None
        }
    }

    /// Handle sending a request to delete the currently selected node.
    fn handle_delete(&mut self) -> Option<Msg> {
        let current_node = self.component.get_current_selected_node()?;
        let path = current_node.data().path.clone();

        let focus_node_after = {
            let num_siblings = current_node.num_siblings();
            // number returned includes the current node
            if num_siblings == 1 {
                // if this returns "None", the to-be deleted path is the root
                current_node
                    .parent()
                    .map(|parent| parent.data().path.clone())
            } else {
                let sibling_idx = current_node.sibling_idx();
                // use the next closest sibling after delete of current node
                let next_child_idx = (sibling_idx + 1).min(
                    num_siblings
                        .saturating_sub(1)
                        .min(sibling_idx.saturating_sub(1)),
                );
                // if we have more than one siblings, it is guranteed to have a parent
                Some(
                    current_node
                        .parent()
                        .unwrap()
                        .child(next_child_idx)
                        .data()
                        .path
                        .clone(),
                )
            }
        };

        Some(Msg::DeleteConfirm(DeleteConfirmMsg::Show(
            path,
            focus_node_after.map(|v| v.to_string_lossy().to_string()),
        )))
    }

    /// Handle a full reload / potential change of the current tree root.
    ///
    /// Also changes focus, if requested.
    fn handle_full_reload(&mut self, data: LIReloadData) -> Option<Msg> {
        let Some(path) = data
            .change_root_path
            .or_else(|| self.get_root_path().map(Path::to_path_buf))
        else {
            debug!("No \"change_root_path\" and no current root, not reloading!");
            return None;
        };
        let focus_node = data
            .focus_node
            .map(PathBuf::from)
            .or_else(|| self.get_selected_path().map(Path::to_path_buf));

        self.component.clear_tree();

        self.trigger_load_with_focus(path, focus_node);

        Some(Msg::ForceRedraw)
    }

    /// Truncate `node`'s path to `root_node`'s path, then split `node`'s path by the separator, iterate over the non-empty components.
    ///
    /// This assumes `node` contains `root_node`!
    fn split_components_root<'a>(
        root_node: &Path,
        node: &'a Path,
    ) -> impl Iterator<Item = std::path::Component<'a>> {
        node.components().skip(root_node.components().count())
    }

    /// Handle reloading of the given path, potentially without changing root, but also change focus.
    ///
    /// If necessary, load all paths in-between.
    fn handle_reload_at(&mut self, data: LIReloadPathData) {
        let path = data.path;
        let Some(root_node) = self.component.get_tree().get_root() else {
            debug!("No root node, not reloading!");
            return;
        };

        if !path.starts_with(&root_node.data().path) {
            debug!("Given path is outside of tree root, not loading!");
            return;
        }

        // because of the if above, we know the node is at least within the tree
        // so it is safe to use the root as the initial starting node.

        // this contains one of 3:
        // - the path of the node itself
        // - the root node's path
        // - the nearest directory node's path
        let mut nearest_path = &root_node.data().path;
        let mut nearest_idx = root_node.idx();
        let mut nearest_match = 0;

        let components_between_root_and_path: Vec<std::path::Component<'_>> =
            Self::split_components_root(&root_node.data().path, &path).collect();

        let mut traverser = Dfs::<OverNode>::new();
        // inital tree walker
        let walker = root_node.walk_with(&mut traverser);

        for node in walker {
            // exact match found, no need to further iterate
            if node.data().path == path {
                nearest_path = &node.data().path;
                nearest_idx = node.idx();
                break;
            }

            // The parent directory node will always contain the wanted path partially
            // skip everything else.
            // Otherwise it might decend into "root/to_delete/another" instead of wanted "root/dir/another".
            if !path.starts_with(&node.data().path) {
                continue;
            }

            for (idx, comp) in
                Self::split_components_root(&root_node.data().path, &node.data().path).enumerate()
            {
                let Some(gotten) = components_between_root_and_path.get(idx) else {
                    break;
                };

                if *gotten == comp && idx > nearest_match {
                    nearest_match = idx;
                    nearest_path = &node.data().path;
                    nearest_idx = node.idx();
                }
            }
        }

        let nearest_path = nearest_path.clone();

        trace!(
            "found nearest match: {:#?}",
            (&path, nearest_match, &nearest_path)
        );

        let depth = components_between_root_and_path
            .len()
            .saturating_sub(nearest_match);
        let depth = u32::try_from(depth).unwrap_or_default();

        let focus_node = if data.change_focus { Some(path) } else { None };

        // unwrap is safe as we literally just gotten the idx from the tree
        // set current node to loading, to indicate such to the user
        self.component
            .get_node_mut(nearest_idx)
            .unwrap()
            .data_mut()
            .is_loading = true;

        self.trigger_subload_with_focus(nearest_path, ScanDepth::Limited(depth), focus_node);
    }

    /// Get the [`NodeIdx`] of a given [`Path`], searches from current tree root.
    fn get_idx_of_path(&self, path: &Path) -> Option<NodeIdx<MusicLibData>> {
        let root_node = self.component.get_tree().get_root()?;

        let mut traverser = Dfs::<OverNode>::new();
        // inital tree walker
        let mut walker = root_node.walk_with(&mut traverser);

        walker.find(|v| v.data().path == path).map(|v| v.idx())
    }

    /// Select, open all parents and open the given node.
    fn select_and_open_node(&mut self, idx: NodeIdx<MusicLibData>) {
        self.component.select(idx);
        self.component.open_all_parents(idx);
        // always open the selected node
        self.handle_right_key(true);
    }

    /// Apply the given data as the root of the tree, resetting the state of the tree.
    ///
    /// This will always replace the root of the tree.
    #[expect(unsafe_code)]
    fn handle_ready(&mut self, data: LINodeReady) -> Msg {
        let vec = data.vec;
        let initial_node = data.focus_node;

        let initial_node = initial_node
            .map(PathBuf::from)
            .or_else(|| self.get_selected_path().map(Path::to_path_buf));

        let (_, tree) = recvec_to_tree(vec);

        self.component.clear_tree();
        // SAFETY: everything is already invalidated and cleared.
        *unsafe { self.component.get_tree_mut() } = tree;

        if let Some(initial_node) = initial_node {
            let idx = self.get_idx_of_path(&initial_node);
            if let Some(idx) = idx {
                self.select_and_open_node(idx);
            } else {
                // requested node is not within the tree, lets try to find the next nearest parent
                self.select_nearest_parent_node(&initial_node);
            }
        } else {
            // always select the root node
            self.component.perform(Cmd::Move(Direction::Down));
            // always open the root node
            self.component.perform(Cmd::Move(Direction::Right));
        }

        Msg::ForceRedraw
    }

    /// Select the next nearest parent node of the given `inital_path`.
    fn select_nearest_parent_node(&mut self, inital_path: &Path) {
        let mut remaining_path = inital_path;
        while let Some(parent) = remaining_path.parent()
            && parent.starts_with(&self.component.get_tree().root().data().path)
        {
            if let Some(idx) = self.get_idx_of_path(parent) {
                self.select_and_open_node(idx);
                break;
            }

            remaining_path = parent;
        }
    }

    /// Apply the given data at the path the data is, potentially without changing root.
    ///
    /// This will replace the root if the given data is starting at the root path.
    #[expect(unsafe_code)]
    fn handle_ready_sub(&mut self, data: LINodeReadySub) -> Option<Msg> {
        let vec = data.vec;

        // let tree_mut = self.component.tree_mut().root_mut();
        let Some(root_path) = self.get_root_path() else {
            // TODO: should we apply it?
            debug!("No root path, not applying");
            return None;
        };

        if !vec.path.exists() {
            // Path does not exist anymore, for example after a paste / delete
            if let Some(idx) = self.get_idx_of_path(&vec.path) {
                // Unwrap is safe because we literally just searched it.
                self.component.get_node_mut(idx).unwrap().prune();
            }
        } else if root_path == vec.path {
            // the given data *is* the root, so we have to replace the whole tree
            self.component.clear_tree();
            // SAFETY: everything is already invalidated and cleared.
            *unsafe { self.component.get_tree_mut() } = recvec_to_tree(vec).1;

            // always select the root node
            self.component.perform(Cmd::Move(Direction::Down));
            // always open the root node
            self.component.perform(Cmd::Move(Direction::Right));
        } else {
            let Some(found_node_idx) = self.get_idx_of_path(&vec.path) else {
                warn!(
                    "Ready node ({}) not found in tree ({})!",
                    vec.path.display(),
                    self.component.get_tree().root().data().path.display()
                );
                return None;
            };

            // try to set a initially selected node
            if self.component.get_current_selected_node().is_none() {
                self.component.perform(Cmd::GoTo(Position::Begin));
            }

            // re-set focus to the removed node, if it had focus
            let is_node_selected = self.component.get_state().selected() == Some(found_node_idx);

            // Unwrap is safe, as we literally just searched the tree for this node
            let mut node_mut = self.component.get_node_mut(found_node_idx).unwrap();

            // TODO: consider using "NodeMut::replace" once available
            // see <https://github.com/orxfun/orx-tree/issues/189>
            let new_idx =
                node_mut.push_sibling_tree(tuirealm_orx_tree::Side::Left, recvec_to_tree(vec).1);
            node_mut.prune();
            // NOTE: we dont need to re-set "is_loading" as the full node gets overwritten with new data, which defaults to "false"

            if data.focus_node.is_none() && is_node_selected {
                self.component.select_no_offset(new_idx);
            }
        }

        if let Some(focus_node) = data.focus_node {
            let idx = self.get_idx_of_path(&focus_node);
            if let Some(idx) = idx {
                self.select_and_open_node(idx);
            } else {
                // requested node is not within the tree, lets try to find the next nearest parent
                self.select_nearest_parent_node(&focus_node);
            }
        }

        Some(Msg::ForceRedraw)
    }

    /// Reply to the request for the currently selected node path.
    fn handle_request_current_node(&self, data: &LIReqNode) {
        let current_node = self.get_selected_path().map(Path::to_path_buf);
        // We dont care if the sending fails. It is used as a one-shot, so we should be the only senders
        // so it should only fail if the receiver is already dropped.
        // We also cannot use "blocking_send" as that panics tokio as this might be in a async runtime context.
        let _ = data.sender.try_send(current_node);
    }

    /// Handle all custom messages.
    fn handle_user_events(&mut self, ev: LIMsg) -> Option<Msg> {
        // handle subscriptions
        match ev {
            LIMsg::Reload(data) => self.handle_full_reload(data),
            LIMsg::ReloadPath(data) => {
                self.handle_reload_at(data);
                Some(Msg::ForceRedraw)
            }
            LIMsg::TreeNodeReady(data) => Some(self.handle_ready(data)),
            LIMsg::TreeNodeReadySub(data) => self.handle_ready_sub(data),
            LIMsg::RequestCurrentPath(data) => {
                self.handle_request_current_node(&data);
                None
            }
            _ => None,
        }
    }
}

impl Component<Msg, UserEvent> for OrxMusicLibraryComponent {
    #[allow(clippy::too_many_lines)]
    fn on(&mut self, ev: Event<UserEvent>) -> Option<Msg> {
        if let Event::User(UserEvent::Forward(Msg::Library(ev))) = ev {
            return self.handle_user_events(ev);
        }

        let config = self.config.clone();
        let keys = &config.read().settings.keys;
        let result = match ev {
            // selection
            Event::Keyboard(keyevent) if keyevent == keys.navigation_keys.left.get() => {
                match self.handle_left_key() {
                    Some(msg) => return Some(msg),
                    None => CmdResult::None,
                }
            }
            Event::Keyboard(keyevent) if keyevent == keys.navigation_keys.right.get() => {
                match self.handle_right_key(false) {
                    Some(msg) => return Some(msg),
                    None => CmdResult::None,
                }
            }
            Event::Keyboard(keyevent) if keyevent == keys.navigation_keys.down.get() => {
                self.perform(Cmd::Move(Direction::Down))
            }
            Event::Keyboard(keyevent) if keyevent == keys.navigation_keys.up.get() => {
                self.perform(Cmd::Move(Direction::Up))
            }
            Event::Keyboard(KeyEvent {
                code: Key::Left,
                modifiers: KeyModifiers::NONE,
            }) => match self.handle_left_key() {
                Some(msg) => return Some(msg),
                None => CmdResult::None,
            },
            Event::Keyboard(KeyEvent {
                code: Key::Right,
                modifiers: KeyModifiers::NONE,
            }) => match self.handle_right_key(false) {
                Some(msg) => return Some(msg),
                None => CmdResult::None,
            },
            Event::Keyboard(KeyEvent {
                code: Key::Down,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::Move(Direction::Down)),
            Event::Keyboard(KeyEvent {
                code: Key::Up,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::Move(Direction::Up)),

            // quick selection movement
            Event::Keyboard(KeyEvent {
                code: Key::PageDown,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::Custom(cmd::PG_DOWN)),
            Event::Keyboard(KeyEvent {
                code: Key::PageUp,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::Custom(cmd::PG_UP)),

            Event::Keyboard(keyevent) if keyevent == keys.navigation_keys.goto_top.get() => {
                self.perform(Cmd::GoTo(Position::Begin))
            }
            Event::Keyboard(keyevent) if keyevent == keys.navigation_keys.goto_bottom.get() => {
                self.perform(Cmd::GoTo(Position::End))
            }
            Event::Keyboard(KeyEvent {
                code: Key::Home,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::GoTo(Position::Begin)),
            Event::Keyboard(KeyEvent {
                code: Key::End,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::GoTo(Position::End)),

            // file modifying
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.delete.get() => {
                return self.handle_delete();
            }
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.yank.get() => {
                self.yank();
                CmdResult::None
            }
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.paste.get() => {
                match self.paste() {
                    Ok(None) => CmdResult::None,
                    Ok(Some(msg)) => return Some(Msg::Library(msg)),
                    Err(err) => return Some(Msg::Library(LIMsg::PasteError(err.to_string()))),
                }
            }

            // music root modification
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.cycle_root.get() => {
                if let Some(path) = self.get_root_path() {
                    return Some(Msg::Library(LIMsg::SwitchRoot(path.to_path_buf())));
                }
                CmdResult::None
            }

            Event::Keyboard(keyevent) if keyevent == keys.library_keys.add_root.get() => {
                if let Some(path) = self.get_root_path() {
                    return Some(Msg::Library(LIMsg::AddRoot(path.to_path_buf())));
                }
                CmdResult::None
            }
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.remove_root.get() => {
                if let Some(path) = self.get_root_path() {
                    return Some(Msg::Library(LIMsg::RemoveRoot(path.to_path_buf())));
                }
                CmdResult::None
            }

            // load more tree
            Event::Keyboard(KeyEvent {
                code: Key::Backspace,
                modifiers: KeyModifiers::NONE,
            }) => {
                if let Some(current_root) = self.get_root_path() {
                    let parent = current_root.parent().unwrap_or(current_root);

                    // only trigger a load if we are not at the root of the filesystem already
                    if current_root != parent {
                        self.trigger_load_with_focus(parent, Some(current_root.to_path_buf()));

                        // to draw the load spinner
                        return Some(Msg::ForceRedraw);
                    }
                }

                // there is no special indicator or message; the download_tracker should force a draw once active
                CmdResult::None
            }
            Event::Keyboard(KeyEvent {
                code: Key::Enter,
                modifiers: KeyModifiers::NONE,
            }) => {
                if let Some(selected_node) = self.get_selected_path()
                    && selected_node.is_dir()
                {
                    self.trigger_load_with_focus(selected_node, None);

                    // to draw the load spinner
                    return Some(Msg::ForceRedraw);
                }

                CmdResult::None
            }

            // search
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.search.get() => {
                if let Some(path) = self.get_root_path() {
                    return Some(Msg::GeneralSearch(GSMsg::PopupShowLibrary(
                        path.to_path_buf(),
                    )));
                }
                CmdResult::None
            }

            Event::Keyboard(keyevent) if keyevent == keys.library_keys.youtube_search.get() => {
                if let Some(path) = self.get_selected_path() {
                    return Some(Msg::YoutubeSearch(YSMsg::InputPopupShow(
                        path.to_path_buf(),
                    )));
                }
                CmdResult::None
            }

            // load into playlist
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.load_dir.get() => {
                if let Some(path) = self.get_selected_path()
                    && path.is_dir()
                {
                    return Some(Msg::Playlist(PLMsg::Add(path.to_path_buf())));
                }
                CmdResult::None
            }
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.load_track.get() => {
                if let Some(path) = self.get_selected_path()
                    && !path.is_dir()
                {
                    return Some(Msg::Playlist(PLMsg::Add(path.to_path_buf())));
                }
                CmdResult::None
            }

            // other
            Event::Keyboard(
                KeyEvent {
                    code: Key::Tab,
                    modifiers: KeyModifiers::NONE,
                }
                | KeyEvent {
                    code: Key::BackTab,
                    modifiers: KeyModifiers::SHIFT,
                },
            ) => return Some(Msg::Library(LIMsg::TreeBlur)),
            Event::Keyboard(keyevent) if keyevent == keys.library_keys.open_tag_editor.get() => {
                if let Some(path) = self.get_selected_path()
                    && !path.is_dir()
                {
                    return Some(Msg::TagEditor(TEMsg::Open(path.to_path_buf())));
                }
                CmdResult::None
            }

            _ => CmdResult::None,
        };
        match result {
            CmdResult::None => None,
            _ => Some(Msg::ForceRedraw),
        }
    }
}