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
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::Ordering;
use std::time::Duration;

use anyhow::{Context, Result, anyhow, bail};
use id3::frame::Lyrics as Id3Lyrics;
#[allow(unused_imports)]
use termusiclib::config::v2::tui::CoverArtProtocol;
use termusiclib::config::v2::tui::keys::Keys;
use termusiclib::config::v2::tui::theme::ThemeWrap;
use termusiclib::config::{ServerOverlay, SharedServerSettings, SharedTuiSettings, TuiOverlay};
use termusiclib::new_database::Database;
use termusiclib::new_database::track_ops::TrackRead;
use termusiclib::player::playlist_helpers::PlaylistTrackSource;
use termusiclib::player::{PlaylistTracks, RunningStatus};
use termusiclib::podcast::{Podcast, PodcastFeed, db::Database as DBPod};
use termusiclib::songtag::SongTag;
use termusiclib::songtag::lrc::Lyric;
use termusiclib::taskpool::TaskPool;
use termusiclib::track::{LyricData, MediaTypesSimple, Track};
use termusiclib::utils::get_app_config_path;
use termusiclib::xywh;
use tokio::sync::mpsc::{UnboundedSender, unbounded_channel};
use tuirealm::terminal::{CrosstermTerminalAdapter, TerminalBridge};

use super::components::TETrack;
use super::tui_cmd::TuiCmd;
use crate::CombinedSettings;
use crate::ui::Application;
use crate::ui::ids::Id;
use crate::ui::model::ports::stream_events::{PortStreamEvents, WrappedStreamEvents};
use crate::ui::model::youtube_options::YoutubeOptions;
use crate::ui::msg::{ConfigEditorLayout, Msg, SearchCriteria};
#[cfg(all(feature = "cover-ueberzug", not(target_os = "windows")))]
use crate::ui::ueberzug::UeInstance;
pub use download_tracker::DownloadTracker;
pub use user_events::UserEvent;

mod download_tracker;
mod playlist;
mod ports;
mod update;
mod user_events;
mod view;
pub mod youtube_options;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum TermusicLayout {
    TreeView,
    DataBase,
    Podcast,
}

/// All data specific to the Database Widget / View
#[derive(Debug)]
pub struct DatabaseWidgetData {
    /// Criteria to search for
    pub criteria: SearchCriteria,
    /// Criteria Search results `(criteria -> this)`
    pub search_results: Vec<String>,
    /// Results of the critea results search `(criteria -> search_results -> this)`
    pub search_tracks: Vec<TrackRead>,
}

impl DatabaseWidgetData {
    /// Reset all search Vectors to a new empty Vector
    ///
    /// (removing allocations)
    pub fn reset_search_results(&mut self) {
        // Reset instead of ".clear" as "clear" does not remove capacity and might not be used again and could potentially be large
        self.search_results = Vec::new();
        self.search_tracks = Vec::new();
    }
}

/// All data specific to the Podcast Widget / View
#[derive(Debug)]
pub struct PodcastWidgetData {
    /// Loaded and displayed Podcast list
    pub podcasts: Vec<Podcast>,
    /// Selected podcast index
    pub podcasts_index: usize,
    /// Podcast Database
    pub db_podcast: DBPod,
    /// Podcast search results
    pub search_results: Option<Vec<PodcastFeed>>,
}

/// All data specific to the Config Editor Widget / View
#[derive(Debug)]
pub struct ConfigEditorData {
    /// All possible file-themes that could be selected
    pub themes: Vec<String>,
    /// The Theme to edit to preview before saving
    pub theme: ThemeWrap,
    /// Last known Config editor layout, for fallbacks when getting from focus is not available
    pub last_layout: ConfigEditorLayout,
    /// The Keybindings to preview before saving
    pub key_config: Keys,
    /// Indicator to prompt a save on config editor exit
    pub config_changed: bool,
}

/// Information about the playback status
#[derive(Debug, Clone)]
pub struct Playback {
    /// The Playlist with all the tracks.
    pub playlist: playlist::TUIPlaylist,
    /// The current Running Status like Playing / Paused
    status: RunningStatus,
    /// The current track, if there is one. Does not need to be in the playlist.
    current_track: Option<Track>,
    current_track_pos: Duration,
}

impl Playback {
    fn new() -> Self {
        Self {
            playlist: playlist::TUIPlaylist::default(),
            status: RunningStatus::default(),
            current_track: None,
            current_track_pos: Duration::ZERO,
        }
    }

    #[must_use]
    pub fn is_stopped(&self) -> bool {
        self.status == RunningStatus::Stopped
    }

    #[must_use]
    #[expect(dead_code)]
    pub fn is_paused(&self) -> bool {
        self.status == RunningStatus::Paused
    }

    #[must_use]
    pub fn status(&self) -> RunningStatus {
        self.status
    }

    pub fn set_status(&mut self, status: RunningStatus) {
        self.status = status;
    }

    #[must_use]
    pub fn current_track(&self) -> Option<&Track> {
        self.current_track.as_ref()
    }

    #[must_use]
    #[expect(dead_code)]
    pub fn current_track_mut(&mut self) -> Option<&mut Track> {
        self.current_track.as_mut()
    }

    pub fn clear_current_track(&mut self) {
        self.current_track.take();
    }

    pub fn set_current_track(&mut self, track: Option<Track>) {
        self.current_track = track;
    }

    /// Set the current track from the playlist, if there is one
    pub fn set_current_track_from_playlist(&mut self) {
        self.set_current_track(self.playlist.current_track().cloned());
    }

    pub fn current_track_pos(&self) -> Duration {
        self.current_track_pos
    }

    pub fn set_current_track_pos(&mut self, pos: Duration) {
        self.current_track_pos = pos;
    }

    /// Load Tracks from a GRPC response.
    ///
    /// Returns `(Position, Tracks[])`.
    ///
    /// # Errors
    ///
    /// - when converting from u64 grpc values to usize fails
    /// - when there is no track-id
    /// - when reading a Track from path or podcast database fails
    pub fn load_from_grpc(
        &mut self,
        info: PlaylistTracks,
        podcast_db: &DBPod,
    ) -> anyhow::Result<()> {
        let current_track_index = usize::try_from(info.current_track_index)
            .context("convert current_track_index(u64) to usize")?;
        let mut playlist_items = Vec::with_capacity(info.tracks.len());

        for (idx, track) in info.tracks.into_iter().enumerate() {
            let at_index_usize =
                usize::try_from(track.at_index).context("convert at_index(u64) to usize")?;
            // assume / require that the tracks are ordered correctly, if not just log a error for now
            if idx != at_index_usize {
                error!("Non-matching \"index\" and \"at_index\"!");
            }

            // this case should never happen with "termusic-server", but grpc marks them as "optional"
            let Some(id) = track.id else {
                bail!("Track does not have a id, which is required to load!");
            };

            let track = match PlaylistTrackSource::try_from(id)? {
                PlaylistTrackSource::Path(v) => Track::read_track_from_path(v)?,
                PlaylistTrackSource::Url(v) => Track::new_radio(&v),
                PlaylistTrackSource::PodcastUrl(v) => {
                    let episode = podcast_db.get_episode_by_url(&v)?;
                    Track::from_podcast_episode(&episode)
                }
            };

            playlist_items.push(track);
        }

        self.playlist.set_tracks(playlist_items);

        // the old server playlist implementation will send `current_track_index: 0`, even if there are not tracks
        // but the new TUI implementation function "set_current_track_index" will refuse to set anything if the index is out-of-bounds
        if !self.playlist.is_empty() {
            self.playlist.set_current_track_index(current_track_index)?;
        }

        self.set_current_track_from_playlist();

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ExtraLyricData {
    pub for_track: PathBuf,
    pub data: LyricData,
    pub selected_idx: usize,
}

impl ExtraLyricData {
    /// Cycle to the next lyric frame and parse it.
    ///
    /// Returns `Some(RawLyric)` if found.
    ///
    /// # Errors
    ///
    /// If there are no frames
    pub fn cycle_lyric(&mut self) -> Result<Option<&Id3Lyrics>> {
        if self.data.raw_lyrics.is_empty() {
            bail!("No lyric frames");
        }

        self.selected_idx += 1;
        if self.selected_idx >= self.data.raw_lyrics.len() {
            self.selected_idx = 0;
        }

        let raw_lyric = self.data.raw_lyrics.get(self.selected_idx);
        self.data.parsed_lyrics = raw_lyric.and_then(|v| Lyric::from_str(&v.text).ok());

        Ok(raw_lyric)
    }
}

/// All data specific to the Tag Editor.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TagEditor {
    /// The current track open in the tag editor.
    pub song: Option<TETrack>,
    /// Stores the result of the songtag fetching.
    pub songtag_results: Vec<SongTag>,
    /// Track whether the Tag Editor modified the current track or not.
    /// Used to force reload of metadata (currently only lyrics)
    pub has_changed: bool,
}

pub type TxToMain = UnboundedSender<Msg>;

pub struct Model {
    /// Indicates that the application must quit
    pub quit: bool,
    /// Tells whether to redraw interface
    pub redraw: bool,
    pub app: Application<Id, Msg, UserEvent>,
    /// Used to draw to terminal
    pub terminal: TerminalBridge<CrosstermTerminalAdapter>,
    pub tx_to_main: TxToMain,
    /// Sender for Player Commands
    pub cmd_to_server_tx: UnboundedSender<TuiCmd>,

    pub config_tui: SharedTuiSettings,
    pub config_server: SharedServerSettings,
    pub db: Database,

    pub layout: TermusicLayout,
    pub dw: DatabaseWidgetData,
    pub podcast: PodcastWidgetData,
    pub config_editor: ConfigEditorData,
    pub tageditor: TagEditor,

    pub current_track_lyric: Option<ExtraLyricData>,
    pub playback: Playback,

    #[cfg(all(feature = "cover-ueberzug", not(target_os = "windows")))]
    pub ueberzug_instance: Option<UeInstance>,
    pub viuer_supported: ViuerSupported,
    pub xywh: xywh::Xywh,

    youtube_options: YoutubeOptions,
    pub download_tracker: DownloadTracker,
    /// Taskpool to limit number of active network requests
    ///
    /// Currently only used for podcast sync & download
    pub taskpool: TaskPool,
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ViuerSupported {
    #[cfg(feature = "cover-viuer-kitty")]
    Kitty,
    #[cfg(feature = "cover-viuer-iterm")]
    ITerm,
    #[cfg(feature = "cover-viuer-sixel")]
    Sixel,
    NotSupported,
}

#[allow(unused)] // "config" may be listed as unused if no "cover-*" features are enabled
fn get_viuer_support(config: &TuiOverlay) -> ViuerSupported {
    #[cfg(feature = "cover-viuer-kitty")]
    if config.cover_protocol_enabled(CoverArtProtocol::Kitty)
        && viuer::KittySupport::None != viuer::get_kitty_support()
    {
        return ViuerSupported::Kitty;
    }
    #[cfg(feature = "cover-viuer-iterm")]
    if config.cover_protocol_enabled(CoverArtProtocol::Iterm2) && viuer::is_iterm_supported() {
        return ViuerSupported::ITerm;
    }
    #[cfg(feature = "cover-viuer-sixel")]
    if config.cover_protocol_enabled(CoverArtProtocol::Sixel) && viuer::is_sixel_supported() {
        return ViuerSupported::Sixel;
    }

    ViuerSupported::NotSupported
}

impl Model {
    #[allow(clippy::too_many_lines)]
    pub fn new(
        config: CombinedSettings,
        cmd_to_server_tx: UnboundedSender<TuiCmd>,
        stream_updates: WrappedStreamEvents,
    ) -> Self {
        let CombinedSettings {
            server: config_server,
            tui: config_tui,
        } = config;
        let path = Self::get_full_path_from_config(&config_server.read());

        let config_tui_read = config_tui.read();

        let viuer_supported = if config_tui_read.cover_features_enabled() {
            get_viuer_support(&config_tui_read)
        } else {
            ViuerSupported::NotSupported
        };

        info!("Using viuer protocol {viuer_supported:#?}");

        #[cfg(all(feature = "cover-ueberzug", not(target_os = "windows")))]
        let ueberzug_instance = if config_tui_read.cover_features_enabled()
            && config_tui_read.cover_protocol_enabled(CoverArtProtocol::Ueberzug)
            && viuer_supported == ViuerSupported::NotSupported
        {
            Some(UeInstance::default())
        } else {
            None
        };

        drop(config_tui_read);

        let db = Database::new_default_path().expect("Open Library Database");
        let db_criteria = SearchCriteria::Artist;
        let terminal = TerminalBridge::new_crossterm().expect("Could not initialize terminal");

        let db_path = get_app_config_path().expect("failed to get podcast db path.");

        let db_podcast = DBPod::new(&db_path).expect("error connecting to podcast db.");

        let podcasts = db_podcast
            .get_podcasts()
            .expect("failed to get podcasts from db.");
        let taskpool = TaskPool::new(usize::from(
            config_server
                .read()
                .settings
                .podcast
                .concurrent_downloads_max
                .get(),
        ));
        let (tx_to_main, rx_to_main) = unbounded_channel();

        let stream_update_port = PortStreamEvents::new(stream_updates);

        let app = Self::init_app(rx_to_main, stream_update_port);

        // This line is required, in order to show the playing message for the first track
        // playlist.set_current_track_index(0);

        let ce_theme = config_tui.read().settings.theme.clone();
        let xywh = xywh::Xywh::from(&config_tui.read().settings.coverart);

        let download_tracker = DownloadTracker::default();

        let mut model = Self {
            app,
            quit: false,
            redraw: true,
            terminal,
            config_server,
            config_tui,

            tageditor: TagEditor::default(),
            youtube_options: YoutubeOptions::default(),
            #[cfg(all(feature = "cover-ueberzug", not(target_os = "windows")))]
            ueberzug_instance,
            viuer_supported,
            db,
            layout: TermusicLayout::TreeView,
            dw: DatabaseWidgetData {
                criteria: db_criteria,
                search_results: Vec::new(),
                search_tracks: Vec::new(),
            },
            podcast: PodcastWidgetData {
                podcasts,
                podcasts_index: 0,
                db_podcast,
                search_results: None,
            },
            config_editor: ConfigEditorData {
                themes: Vec::new(),
                theme: ce_theme,
                last_layout: ConfigEditorLayout::default(),
                key_config: Keys::default(),
                config_changed: false,
            },
            taskpool,
            tx_to_main,
            download_tracker,
            current_track_lyric: None,
            playback: Playback::new(),
            cmd_to_server_tx,
            xywh,
        };

        model.new_library_scan_dir(path, None);

        model
            .mount_main()
            .expect("Expected all main component to mount correctly");

        model
    }

    #[inline]
    pub fn get_combined_settings(&self) -> CombinedSettings {
        CombinedSettings {
            server: self.config_server.clone(),
            tui: self.config_tui.clone(),
        }
    }

    /// Get the first music directory or the cli provided music dir resolved
    pub fn get_full_path_from_config(config: &ServerOverlay) -> PathBuf {
        let mut full_path = String::new();

        if let Some(first_music_dir) = config.get_first_music_dir() {
            full_path = shellexpand::path::tilde(first_music_dir)
                .to_string_lossy()
                .to_string();
        }

        PathBuf::from(full_path)
    }

    /// Run startup tasks:
    /// - Extract Themes
    /// - Start Database scan
    /// - Generate playlist component data
    pub fn init(&mut self) {
        if let Err(e) = Self::theme_extract_all() {
            self.mount_error_popup(e.context("theme save"));
        }
        self.scan_all_music_roots();
        self.playlist_sync();
    }

    /// Trigger a database scan for all music roots.
    fn scan_all_music_roots(&self) {
        let config_server = self.config_server.read();
        for dir in &config_server.settings.player.music_dirs {
            let absolute_dir = shellexpand::path::tilde(dir);

            if let Err(err) = self.db.scan_path(&absolute_dir, &config_server, false) {
                error!(
                    "Error scanning path {:#?}: {err:#?}",
                    absolute_dir.display()
                );
            }
        }
    }

    /// Initialize terminal
    pub fn init_terminal(&mut self) {
        let original_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |panic| {
            Self::hook_reset_terminal();
            original_hook(panic);
        }));
        let _drop = self.terminal.enable_raw_mode();
        let _drop = self.terminal.enter_alternate_screen();
        // required as "enter_alternate_screen" always enabled mouse-capture
        let _drop = self.terminal.disable_mouse_capture();
        let _drop = self.terminal.clear_screen();
        crate::TERMINAL_ALTERNATE_MODE.store(true, Ordering::SeqCst);
    }

    /// Finalize terminal for hooks like panic or CTRL+C
    pub fn hook_reset_terminal() {
        let mut terminal_clone =
            TerminalBridge::new_crossterm().expect("Could not initialize terminal");
        let _drop = terminal_clone.disable_raw_mode();
        let _drop = terminal_clone.leave_alternate_screen();
        crate::TERMINAL_ALTERNATE_MODE.store(false, Ordering::SeqCst);
    }

    /// Finalize terminal
    pub fn finalize_terminal(&mut self) {
        let _drop = self.terminal.disable_raw_mode();
        let _drop = self.terminal.leave_alternate_screen();
        crate::TERMINAL_ALTERNATE_MODE.store(false, Ordering::SeqCst);
    }

    /// Force a redraw of the entire model
    pub fn force_redraw(&mut self) {
        self.redraw = true;
    }

    /// Send a command to request the Track Progress and set the titles to the current state.
    #[inline]
    pub fn request_progress(&mut self) {
        self.command(TuiCmd::GetProgress);
    }

    /// Update all the places that need to be updated after a current track change or running status change.
    pub fn player_update_current_track_after(&mut self) {
        if let Err(e) = self.update_photo() {
            self.mount_error_popup(e.context("update_photo"));
        }
        self.progress_update_title();
        self.lyric_update_title();
        self.lyric_update();
        self.update_playing_song();
    }

    /// Send a [`TogglePause`](TuiCmd::TogglePause) command, if the conditions are right.
    pub fn player_toggle_pause(&mut self) {
        if self.playback.playlist.is_empty() && self.playback.current_track().is_none() {
            return;
        }

        self.command(TuiCmd::TogglePause);
    }

    /// Send a [`SkipPrevious`](TuiCmd::SkipPrevious) command.
    pub fn player_previous(&mut self) {
        self.command(TuiCmd::SkipPrevious);
    }

    /// Send a command to the `MusicPlayerService` (via the Client)
    pub fn command(&mut self, cmd: TuiCmd) {
        if let Err(e) = self.cmd_to_server_tx.send(cmd) {
            self.mount_error_popup(anyhow!(e));
        }
    }

    pub fn is_radio(&self) -> bool {
        if let Some(track) = self.playback.current_track()
            && track.media_type() == MediaTypesSimple::LiveRadio
        {
            return true;
        }
        false
    }
}