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
use std::sync::LazyLock;

use anyhow::{Result, anyhow};
use regex::Regex;
use termusiclib::common::const_unknown::{UNKNOWN_ARTIST, UNKNOWN_TITLE};
use termusiclib::config::SharedTuiSettings;
use termusiclib::player::RunningStatus;
use termusiclib::podcast::episode::Episode;
use termusiclib::track::MediaTypesSimple;
use termusiclib::track::{MediaTypes, Track};
use tui_realm_stdlib::Textarea;
use tuirealm::command::{Cmd, Direction, Position};
use tuirealm::event::{Key, KeyEvent, KeyModifiers};
use tuirealm::props::{
    Alignment, AttrValue, Attribute, BorderType, Borders, PropPayload, PropValue, Style, TextSpan,
};
use tuirealm::{Component, Event, MockComponent, State, StateValue};

use super::TETrack;
use crate::ui::ids::Id;
use crate::ui::model::{ExtraLyricData, UserEvent};
use crate::ui::msg::{LyricMsg, Msg};
use crate::ui::{Model, model::TermusicLayout};

/// Regex for finding <br/> tags -- also captures any surrounding
/// line breaks
static RE_BR_TAGS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"((\r\n)|\r|\n)*<br */?>((\r\n)|\r|\n)*").unwrap());

/// Regex for finding HTML tags
static RE_HTML_TAGS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<[^<>]*>").unwrap());

/// Regex for finding more than two line breaks
static RE_MULT_LINE_BREAKS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"((\r\n)|\r|\n){3,}").unwrap());

#[derive(MockComponent)]
pub struct Lyric {
    component: Textarea,
    config: SharedTuiSettings,
}

impl Lyric {
    pub fn new(config: SharedTuiSettings) -> Self {
        let component = {
            let config = config.read();
            Textarea::default()
                .borders(
                    Borders::default()
                        .color(config.settings.theme.lyric_border())
                        .modifiers(BorderType::Rounded),
                )
                .background(config.settings.theme.lyric_background())
                .foreground(config.settings.theme.lyric_foreground())
                .inactive(Style::new().bg(config.settings.theme.lyric_background()))
                .title(" Lyrics ", Alignment::Left)
                // .wrap(true)
                .step(4)
                .highlighted_str(&config.settings.theme.style.playlist.highlight_symbol)
                .text_rows([TextSpan::new(format!("{}.", RunningStatus::Stopped))])
        };

        Self { component, config }
    }
}

impl Component<Msg, UserEvent> for Lyric {
    fn on(&mut self, ev: Event<UserEvent>) -> Option<Msg> {
        let config = self.config.clone();
        let keys = &config.read().settings.keys;
        let _cmd_result = match ev {
            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)),
            Event::Keyboard(KeyEvent {
                code: Key::PageDown,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::Scroll(Direction::Down)),
            Event::Keyboard(KeyEvent {
                code: Key::PageUp,
                modifiers: KeyModifiers::NONE,
            }) => self.perform(Cmd::Scroll(Direction::Up)),
            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)),
            Event::Keyboard(KeyEvent {
                code: Key::Tab,
                modifiers: KeyModifiers::NONE,
            }) => return Some(Msg::LyricMessage(LyricMsg::TextAreaBlurDown)),
            Event::Keyboard(KeyEvent {
                code: Key::BackTab,
                modifiers: KeyModifiers::SHIFT,
            }) => return Some(Msg::LyricMessage(LyricMsg::TextAreaBlurUp)),

            Event::Keyboard(key) if key == keys.navigation_keys.down.get() => {
                self.perform(Cmd::Move(Direction::Down))
            }
            Event::Keyboard(key) if key == keys.navigation_keys.up.get() => {
                self.perform(Cmd::Move(Direction::Up))
            }

            Event::Keyboard(key) if key == keys.navigation_keys.goto_top.get() => {
                self.perform(Cmd::GoTo(Position::Begin))
            }
            Event::Keyboard(key) if key == keys.navigation_keys.goto_bottom.get() => {
                self.perform(Cmd::GoTo(Position::End))
            }
            _ => return None,
        };
        // "Textarea::perform" currently always returns "CmdResult::None", so always redraw on event
        // see https://github.com/veeso/tui-realm-stdlib/issues/27
        Some(Msg::ForceRedraw)
    }
}

impl Model {
    /// Remount and reload the lyrics from the current track.
    pub fn lyric_reload(&mut self) {
        assert!(
            self.app
                .remount(
                    Id::Lyric,
                    Box::new(Lyric::new(self.config_tui.clone())),
                    Vec::new()
                )
                .is_ok()
        );
        self.lyric_update_title();
        self.lyric_update();
    }

    /// Force reload lyrics from file. For example after a Tag Editor exit.
    ///
    /// If the current track type is [`Track`], then also unset the Lyric cache for the current track's path.
    pub fn lyric_reload_from_file(&mut self) {
        info!("Forcing reload of lyrics");
        self.current_track_lyric.take();

        if let Some(track) = self.playback.current_track().and_then(|v| v.as_track()) {
            Track::unset_cache_for_path(track.path());
        }

        self.lyric_reload();
    }

    pub fn lyric_update_for_podcast_by_current_track(&mut self) {
        let mut need_update = false;
        let mut pod_title = String::new();
        let mut ep_for_lyric = Episode::default();
        if let Some(track) = self.playback.current_track()
            && let Some(podcast_data) = track.as_podcast()
        {
            let url = podcast_data.url();
            'outer: for pod in &self.podcast.podcasts {
                for ep in &pod.episodes {
                    if ep.url == url {
                        pod_title.clone_from(&pod.title);
                        ep_for_lyric = ep.clone();
                        need_update = true;
                        break 'outer;
                    }
                }
            }
        }

        if need_update {
            self.lyric_update_for_episode_after(&pod_title, &ep_for_lyric);
        }

        self.lyric_update_title();
    }

    pub fn lyric_update_for_podcast(&mut self) -> Result<()> {
        if self.podcast.podcasts.is_empty() {
            return Ok(());
        }
        if let Ok(State::One(StateValue::Usize(episode_index))) = self.app.state(&Id::Episode) {
            let podcast_selected = self
                .podcast
                .podcasts
                .get(self.podcast.podcasts_index)
                .ok_or_else(|| anyhow!("get podcast selected failed."))?
                .clone();
            let episode_selected = podcast_selected
                .episodes
                .get(episode_index)
                .ok_or_else(|| anyhow!("get episode selected failed."))?;

            self.lyric_update_for_episode_after(&podcast_selected.title, episode_selected);
        }

        self.lyric_update_title();
        Ok(())
    }

    pub fn lyric_update_for_episode_after(&mut self, po_title: &str, ep: &Episode) {
        // convert <br/> tags to a single line break
        let br_to_lb = RE_BR_TAGS.replace_all(&ep.description, "\n");

        // strip all HTML tags
        let stripped_tags = RE_HTML_TAGS.replace_all(&br_to_lb, "");

        // convert HTML entities (e.g., &amp;)
        let decoded = match escaper::decode_html(&stripped_tags) {
            Err(_) => stripped_tags.to_string(),
            Ok(s) => s,
        };

        // remove anything more than two line breaks (i.e., one blank line)
        let no_line_breaks = RE_MULT_LINE_BREAKS.replace_all(&decoded, "\n\n");

        let (term_width, _) = viuer::terminal_size();
        let term_width = usize::from(term_width);
        let lyric_width = term_width * 3 / 5;
        let lines_vec: Vec<_> = no_line_breaks.split('\n').collect();
        let mut short_string_vec: Vec<_> = Vec::new();
        for line in lines_vec {
            let unicode_width = unicode_width::UnicodeWidthStr::width(line);
            if unicode_width > lyric_width {
                let mut string_tmp = textwrap::wrap(line, lyric_width);
                short_string_vec.append(&mut string_tmp);
            } else {
                short_string_vec.push(std::borrow::Cow::Borrowed(line));
            }
        }

        let lines_textspan_len = short_string_vec.len();
        let lines_textspan = short_string_vec
            .into_iter()
            .map(|l| PropValue::TextSpan(TextSpan::from(l)));

        let mut final_vec: Vec<_> = Vec::with_capacity(7 + lines_textspan_len);
        final_vec.push(PropValue::TextSpan(TextSpan::from(po_title).bold()));
        final_vec.push(PropValue::TextSpan(TextSpan::from(&ep.title).bold()));
        final_vec.push(PropValue::TextSpan(TextSpan::from("   ")));

        if let Some(date) = ep.pubdate {
            final_vec.push(PropValue::TextSpan(
                TextSpan::from(format!("Published: {}", date.format("%B %-d, %Y"))).italic(),
            ));
        }

        final_vec.push(PropValue::TextSpan(
            TextSpan::from(format!("Duration: {}", ep.format_duration())).italic(),
        ));

        final_vec.push(PropValue::TextSpan(TextSpan::from("   ")));
        final_vec.push(PropValue::TextSpan(TextSpan::from("Description:").bold()));
        final_vec.extend(lines_textspan);

        let _ = self.app.attr(
            &Id::Lyric,
            Attribute::Text,
            AttrValue::Payload(PropPayload::Vec(final_vec)),
        );
    }

    /// Update lyrics. Needs to be run each time:
    /// - a new playback position is available
    /// - play state changed to / from "stopped"
    /// - track change
    ///
    /// This function does not handle setting the lyric title. See [`lyric_update_title`](Model::lyric_update_title).
    pub fn lyric_update(&mut self) {
        const NO_LYRICS: &str = "No lyrics available.";

        // this should be a different component
        if self.layout == TermusicLayout::Podcast {
            if let Err(e) = self.lyric_update_for_podcast() {
                self.mount_error_popup(e.context("lyric update for podcast"));
            }
            return;
        }
        if self.playback.is_stopped() {
            self.lyric_set_lyric("Stopped.");
            return;
        }
        if let Some(track) = self.playback.current_track() {
            // radio only needs to be updated on track change, which is handled in a different function
            if MediaTypesSimple::LiveRadio == track.media_type() {
                return;
            }

            if self
                .current_track_lyric
                .as_ref()
                .is_none_or(|extra| track.as_track().is_none_or(|v| extra.for_track != v.path()))
            {
                self.current_track_lyric.take();
                if track.as_track().is_none() {
                    self.lyric_set_lyric(NO_LYRICS);
                    return;
                }

                if let Ok(Some(data)) = track.get_lyrics() {
                    self.current_track_lyric = Some(ExtraLyricData {
                        for_track: track.as_track().unwrap().path().to_owned(),
                        data: (*data).clone(),
                        selected_idx: 0,
                    });
                } else {
                    self.lyric_set_lyric(NO_LYRICS);
                    return;
                }
            }

            // by this point "current_track_lyric" is definitely "Some()"

            let extra = self.current_track_lyric.as_ref().unwrap();

            let Some(parsed_lyrics) = &extra.data.parsed_lyrics else {
                self.lyric_set_lyric(NO_LYRICS);
                return;
            };

            if parsed_lyrics.captions.is_empty() {
                self.lyric_set_lyric(NO_LYRICS);
                return;
            }

            let mut line = String::new();

            if let Some(l) = parsed_lyrics.get_text(self.playback.current_track_pos()) {
                line = l.to_string();
            }

            self.lyric_set_lyric(line);
        }
    }

    /// Update the lyric field to show Radio information.
    ///
    /// Needs to be run on:
    /// - track change from / to radio
    pub fn lyric_update_for_radio<T: AsRef<str>>(&mut self, radio_title: T) {
        if let Some(song) = self.playback.current_track()
            && MediaTypesSimple::LiveRadio == song.media_type()
        {
            let radio_title = radio_title.as_ref();
            if radio_title.is_empty() {
                self.lyric_set_lyric("Radio");
            } else {
                self.lyric_set_lyric(format!("Currently Playing: {radio_title}"));
            }
        }
    }

    /// Set the given text as the current displayed lyric text.
    fn lyric_set_lyric<T: Into<String>>(&mut self, text: T) {
        let text = text.into();
        self.app
            .attr(
                &Id::Lyric,
                Attribute::Text,
                AttrValue::Payload(PropPayload::Vec(vec![PropValue::TextSpan(TextSpan::from(
                    &text,
                ))])),
            )
            .ok();
    }

    pub fn lyric_cycle(&mut self) {
        if let Some(extra) = self.current_track_lyric.as_mut()
            && let Some(f) = extra.cycle_lyric().ok().flatten()
        {
            let lang_ext = f.description.clone();
            self.update_show_message_timeout(
                "Lyric switch successful",
                format!("{lang_ext} lyric is showing").as_str(),
                None,
            );
        }
    }
    pub fn lyric_adjust_delay(&mut self, offset: i64) {
        let time_pos = self.playback.current_track_pos();
        if let Some(track) = self.playback.current_track() {
            let Ok(mut te_track) = TETrack::try_from(track) else {
                debug!("Could not adjust delay because it is not a music track!");
                return;
            };
            if te_track
                .lyric_set_with_extra(self.current_track_lyric.as_ref())
                .is_none()
            {
                debug!(
                    "Could not adjust delay because of mismatching extra data and current track!"
                );
                return;
            }
            te_track.lyric_adjust_delay(time_pos, offset);
            if let Err(e) = te_track.save_tag() {
                self.mount_error_popup(e.context("adjust lyric delay"));
            }
            self.current_track_lyric = Some(te_track.into_extra_lyric_data());
        }
    }

    const LYRIC_PODCAST_TITLE: &str = " Details: ";

    /// Update the Lyric Component's title.
    ///
    /// Needs to be run on:
    /// - running status change
    /// - track change
    /// - switch from/to podcast layout
    pub fn lyric_update_title(&mut self) {
        let track = self.playback.current_track();

        // this should be a different component
        if self.layout == TermusicLayout::Podcast {
            self.lyric_title_set(Self::LYRIC_PODCAST_TITLE.to_string());
            return;
        }

        if self.playback.is_stopped() || track.is_none() {
            self.lyric_title_set(" No track is playing ".to_string());
            return;
        }

        let track = track.unwrap();

        let lyric_title = match track.inner() {
            MediaTypes::Track(_track_data) => {
                let artist = track.artist().unwrap_or(UNKNOWN_ARTIST);
                let title = track.title().unwrap_or(UNKNOWN_TITLE);
                format!(" Lyrics of {artist:^.20} - {title:^.20} ")
            }
            MediaTypes::Radio(_radio_track_data) => " Live Radio ".to_string(),
            MediaTypes::Podcast(_podcast_track_data) => Self::LYRIC_PODCAST_TITLE.to_string(),
        };
        self.lyric_title_set(lyric_title);
    }

    /// Set a Title for the Lyric Component.
    fn lyric_title_set(&mut self, lyric_title: String) {
        self.app
            .attr(
                &Id::Lyric,
                Attribute::Title,
                AttrValue::Title((lyric_title, Alignment::Center)),
            )
            .ok();
    }
}