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
use crate::config::Settings;
use anyhow::{anyhow, bail, Result};
use lazy_static::lazy_static;
use pinyin::ToPinyin;
use regex::Regex;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Instant;
use std::{
    ffi::OsStr,
    process::{Child, Command},
};
use tuirealm::props::Color;
use tuirealm::tui::layout::{Constraint, Direction, Layout, Rect};
use unicode_segmentation::UnicodeSegmentation;

lazy_static! {
    /**
     * Regex matches:
     * - group 1: Red
     * - group 2: Green
     * - group 3: Blue
     */
    static ref COLOR_HEX_REGEX: Regex = Regex::new(r"#(:?[0-9a-fA-F]{2})(:?[0-9a-fA-F]{2})(:?[0-9a-fA-F]{2})").unwrap();
}

pub struct DownloadTracker {
    items: HashSet<String>,
    pub time_stamp_for_cache: Instant,
}

impl Default for DownloadTracker {
    fn default() -> Self {
        let items = HashSet::new();
        let time_stamp_for_cache = Instant::now();
        Self {
            items,
            time_stamp_for_cache,
        }
    }
}

impl DownloadTracker {
    pub fn increase_one(&mut self, url: &str) {
        self.items.insert(url.to_string());
    }

    pub fn decrease_one(&mut self, url: &str) {
        self.items.remove(url);
    }

    pub fn contains(&self, url: &str) -> bool {
        self.items.contains(url)
    }

    pub fn visible(&self) -> bool {
        !self.items.is_empty()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn message_sync_success(&self) -> String {
        let len = self.items.len();
        if len > 0 {
            format!(
                " 1 of {} feeds was synced successfully! {len} are still running.",
                len + 1,
            )
        } else {
            " All feeds were synced successfully! ".to_string()
        }
    }
    pub fn message_feeds_added(&self) -> String {
        let len = self.items.len();
        if len > 0 {
            format!(
                " 1 of {} feeds was added successfully! {len} are still running.",
                len + 1,
            )
        } else {
            " All feeds were added successfully! ".to_string()
        }
    }

    pub fn message_feed_sync_failed(&self) -> String {
        let len = self.items.len();
        if len > 0 {
            format!(" 1 feed sync failed. {len} are still running. ",)
        } else {
            " 1 feed sync failed. ".to_string()
        }
    }

    pub fn message_sync_start(&self) -> String {
        let len = self.items.len();
        if len > 1 {
            format!(" {len} feeds are being fetching... ",)
        } else {
            " 1 feed is being fetching... ".to_string()
        }
    }

    pub fn message_download_start(&self, title: &str) -> String {
        let len = self.items.len();
        if len > 1 {
            format!(" {len} items downloading... ")
        } else {
            format!(" {len} item {title:^.20} downloading...",)
        }
    }

    pub fn message_download_complete(&self) -> String {
        let len = self.items.len();
        if len > 0 {
            format!(
                " 1 of {} Download Success! {len} is still running.",
                len + 1,
            )
        } else {
            " All Downloads Success! ".to_string()
        }
    }
    pub fn message_download_error_response(&self, title: &str) -> String {
        let len = self.items.len();
        if len > 0 {
            format!(" 1 item {title:^.10} download error! No response from website. {len} is still running. ",)
        } else {
            format!(" {title:^.20} download error. No response from website.")
        }
    }
    pub fn message_download_error_file_create(&self, title: &str) -> String {
        let len = self.items.len();

        if len > 0 {
            format!(
                " 1 item {title:^.10} download error! Cannot create file. {len} is still running. "
            )
        } else {
            format!(" {title:^.20} download error. Cannot create file")
        }
    }

    pub fn message_download_error_file_write(&self, title: &str) -> String {
        let len = self.items.len();

        if len > 0 {
            format!(
                " 1 item {title:^.10} download error! Cannot write to file. {len} is still running. "
            )
        } else {
            format!(" {title:^.20} download error. Cannot write to file")
        }
    }

    pub fn message_download_error_embed_data(&self, title: &str) -> String {
        let len = self.items.len();

        if len > 0 {
            format!(
                " 1 item {title:^.10} download error! Cannot embed data to file. {len} is still running. "
            )
        } else {
            format!(" {title:^.20} download error. Cannot embed data to file.")
        }
    }
}

pub fn get_pin_yin(input: &str) -> String {
    let mut b = String::new();
    for (index, f) in input.to_pinyin().enumerate() {
        match f {
            Some(p) => {
                b.push_str(p.plain());
            }
            None => {
                if let Some(c) = input.to_uppercase().chars().nth(index) {
                    b.push(c);
                }
            }
        }
    }
    b
}

/// # Panics
/// panics could happen when color parse failed
pub fn parse_hex_color(color: &str) -> Option<Color> {
    COLOR_HEX_REGEX.captures(color).map(|groups| {
        Color::Rgb(
            u8::from_str_radix(groups.get(1).unwrap().as_str(), 16)
                .ok()
                .unwrap(),
            u8::from_str_radix(groups.get(2).unwrap().as_str(), 16)
                .ok()
                .unwrap(),
            u8::from_str_radix(groups.get(3).unwrap().as_str(), 16)
                .ok()
                .unwrap(),
        )
    })
}

pub fn filetype_supported(current_node: &str) -> bool {
    let p = Path::new(current_node);

    if p.starts_with("http") {
        return true;
    }

    #[cfg(any(feature = "mpv", feature = "gst"))]
    if let Some(ext) = p.extension() {
        if ext == "opus" {
            return true;
        }
        if ext == "aiff" {
            return true;
        }
    }

    match p.extension() {
        Some(ext) if ext == "mkv" || ext == "mka" => true,
        Some(ext) if ext == "mp3" => true,
        // Some(ext) if ext == "aiff" => true,
        Some(ext) if ext == "flac" => true,
        Some(ext) if ext == "m4a" => true,
        Some(ext) if ext == "aac" => true,
        // Some(ext) if ext == "opus" => true,
        Some(ext) if ext == "ogg" => true,
        Some(ext) if ext == "wav" => true,
        Some(ext) if ext == "webm" => true,
        Some(_) | None => false,
    }
}

pub fn is_playlist(current_node: &str) -> bool {
    let p = Path::new(current_node);

    match p.extension() {
        Some(ext) if ext == "m3u" => true,
        Some(ext) if ext == "m3u8" => true,
        Some(ext) if ext == "pls" => true,
        Some(ext) if ext == "asx" => true,
        Some(ext) if ext == "xspf" => true,
        Some(_) | None => false,
    }
}

///
/// Get block
// pub fn get_block<'a>(props: &Borders, title: (String, Alignment), focus: bool) -> Block<'a> {
//     Block::default()
//         .borders(props.sides)
//         .border_style(if focus {
//             props.style()
//         } else {
//             Style::default().fg(Color::Reset).bg(Color::Reset)
//         })
//         .border_type(props.modifiers)
//         .title(title.0)
//         .title_alignment(title.1)
// }

// Draw an area (WxH / 3) in the middle of the parent area
pub fn draw_area_in_relative(parent: Rect, width: u16, height: u16) -> Rect {
    let new_area = Layout::default()
        .direction(Direction::Vertical)
        .constraints(
            [
                Constraint::Percentage((100 - height) / 2),
                Constraint::Percentage(height),
                Constraint::Percentage((100 - height) / 2),
            ]
            .as_ref(),
        )
        .split(parent);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints(
            [
                Constraint::Percentage((100 - width) / 2),
                Constraint::Percentage(width),
                Constraint::Percentage((100 - width) / 2),
            ]
            .as_ref(),
        )
        .split(new_area[1])[1]
}

pub fn draw_area_in_absolute(parent: Rect, width: u16, height: u16) -> Rect {
    let new_area = Layout::default()
        .direction(Direction::Vertical)
        .constraints(
            [
                Constraint::Length((parent.height - height) / 2),
                Constraint::Length(height),
                Constraint::Length((parent.height - height) / 2),
            ]
            .as_ref(),
        )
        .split(parent);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints(
            [
                Constraint::Length((parent.width - width) / 2),
                Constraint::Length(width),
                Constraint::Length((parent.width - width) / 2),
            ]
            .as_ref(),
        )
        .split(new_area[1])[1]
}

pub fn draw_area_top_right_absolute(parent: Rect, width: u16, height: u16) -> Rect {
    let new_area = Layout::default()
        .direction(Direction::Vertical)
        .constraints(
            [
                Constraint::Length(1),
                Constraint::Length(height),
                Constraint::Length(parent.height - height - 1),
            ]
            .as_ref(),
        )
        .split(parent);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints(
            [
                Constraint::Length(parent.width - width - 1),
                Constraint::Length(width),
                Constraint::Length(1),
            ]
            .as_ref(),
        )
        .split(new_area[1])[1]
}

pub fn get_parent_folder(filename: &str) -> String {
    let parent_folder: PathBuf;
    let path_old = Path::new(filename);

    if path_old.is_dir() {
        parent_folder = path_old.to_path_buf();
        return parent_folder.to_string_lossy().to_string();
    }
    match path_old.parent() {
        Some(p) => parent_folder = p.to_path_buf(),
        None => parent_folder = std::env::temp_dir(),
    }
    parent_folder.to_string_lossy().to_string()
}

pub fn get_app_config_path() -> Result<PathBuf> {
    let mut path = dirs::config_dir().ok_or_else(|| anyhow!("failed to find os config dir."))?;
    path.push("termusic");

    if !path.exists() {
        std::fs::create_dir_all(&path)?;
    }
    Ok(path)
}

fn get_podcast_save_path(config: &Settings) -> Result<PathBuf> {
    let full_path = shellexpand::tilde(&config.podcast_dir).to_string();
    let full_path_pathbuf = PathBuf::from(full_path);
    if !full_path_pathbuf.exists() {
        std::fs::create_dir_all(&full_path_pathbuf)?;
    }
    Ok(full_path_pathbuf)
}

pub fn create_podcast_dir(config: &Settings, pod_title: String) -> Result<PathBuf> {
    match get_podcast_save_path(config) {
        Ok(mut download_path) => {
            download_path.push(pod_title);
            match std::fs::create_dir_all(&download_path) {
                Ok(()) => Ok(download_path),
                Err(e) => bail!("Error in creating podcast feeds download dir: {e}"),
            }
        }
        Err(e) => bail!("Error in creating podcast download dir: {e}"),
    }
}

pub fn playlist_get_vec(current_node: &str) -> Result<Vec<String>> {
    let p = Path::new(current_node);
    let p_base = p.parent().ok_or_else(|| anyhow!("cannot find path root"))?;
    let str = std::fs::read_to_string(p)?;
    let items =
        crate::playlist::decode(&str).map_err(|e| anyhow!("playlist decode error: {}", e))?;
    let mut vec = vec![];
    for item in items {
        if let Ok(pathbuf) = playlist_get_absolute_pathbuf(&item, p_base) {
            vec.push(pathbuf.to_string_lossy().to_string());
        }
    }
    Ok(vec)
}

fn playlist_get_absolute_pathbuf(item: &str, p_base: &Path) -> Result<PathBuf> {
    let url_decoded = urlencoding::decode(item)?.into_owned();
    let mut url = url_decoded.clone();
    let mut pathbuf = PathBuf::from(p_base);
    if url_decoded.starts_with("http") {
        return Ok(PathBuf::from(url_decoded));
        // bail!("http not supported");
    }
    if url_decoded.starts_with("file") {
        url = url_decoded.replace("file://", "");
    }
    if Path::new(&url).is_relative() {
        pathbuf.push(url);
    } else {
        pathbuf = PathBuf::from(url);
    }
    Ok(pathbuf)
}

/// Some helper functions for dealing with Unicode strings.
#[allow(clippy::module_name_repetitions)]
pub trait StringUtils {
    fn substr(&self, start: usize, length: usize) -> String;
    fn grapheme_len(&self) -> usize;
}

impl StringUtils for String {
    /// Takes a slice of the String, properly separated at Unicode
    /// grapheme boundaries. Returns a new String.
    fn substr(&self, start: usize, length: usize) -> String {
        return self
            .graphemes(true)
            .skip(start)
            .take(length)
            .collect::<String>();
    }

    /// Counts the total number of Unicode graphemes in the String.
    fn grapheme_len(&self) -> usize {
        return self.graphemes(true).count();
    }
}

/// Spawn a detached process
/// # Panics
/// panics when spawn server failed
pub fn spawn_process<A: IntoIterator<Item = S> + Clone, S: AsRef<OsStr>>(
    prog: &Path,
    superuser: bool,
    shout_output: bool,
    args: A,
) -> std::io::Result<Child> {
    let mut cmd = if superuser {
        let mut cmd_t = Command::new("sudo");
        cmd_t.arg(prog);
        cmd_t
    } else {
        Command::new(prog)
    };
    if !shout_output {
        cmd.stdout(Stdio::null());
        cmd.stderr(Stdio::null());
    }

    cmd.args(args);
    cmd.spawn()
}

#[cfg(test)]
#[allow(clippy::non_ascii_literal)]
mod tests {

    use crate::utils::get_pin_yin;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_pin_yin() {
        assert_eq!(get_pin_yin("陈一发儿"), "chenyifaer".to_string());
        assert_eq!(get_pin_yin("Gala乐队"), "GALAledui".to_string());
        assert_eq!(get_pin_yin("乐队Gala乐队"), "leduiGALAledui".to_string());
        assert_eq!(get_pin_yin("Annett Louisan"), "ANNETT LOUISAN".to_string());
    }

    use super::*;

    #[test]
    fn test_utils_ui_draw_area_in() {
        let area: Rect = Rect::new(0, 0, 1024, 512);
        let child: Rect = draw_area_in_relative(area, 75, 30);
        assert_eq!(child.x, 43);
        assert_eq!(child.y, 63);
        assert_eq!(child.width, 271);
        assert_eq!(child.height, 54);
    }
}