bckplayer 0.1.0

A cross-platform CLI media player interface for VLC
Documentation
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
use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;

use crate::types::{LogEntry};
use crate::playlists::PlaylistItem;

/// Unified command enum that represents all possible actions in the application
/// This replaces both the old Command enum and AppEvent enum for a unified interface
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    // Playback controls
    Play,
    Pause,
    Stop,
    Toggle, // Play/Pause toggle
    
    // Media loading
    Open(String),
    Load(String),
    
    // Volume controls
    Volume(f64),
    VolumeUp,
    VolumeDown,
    Mute,
    Unmute,
    
    // Seeking
    Seek(f64),
    SeekTo(f64),
    Forward(f64),
    Backward(f64),
    SeekForward,  // From old AppEvent - uses default step
    SeekBackward, // From old AppEvent - uses default step
    
    // Speed controls
    Speed(f64),
    SpeedUp,
    SpeedDown,
    SpeedReset,
    ResetSpeed, // Alias for SpeedReset
    
    // Display controls
    Fullscreen,
    Windowed,
    ToggleFullscreen,
    Loop,
    ToggleLoop,
    
    // Application controls
    Quit,
    Help,
    ShowHelp,    // From old AppEvent
    HideHelp,    // From old AppEvent
    
    // Connection controls
    Connect(String, Option<u16>),
    Disconnect,
    TestConnection,
    
    // Configuration
    Config,
    Save,
    Reload,
    ShowConfig,    // From old AppEvent
    HideConfig,    // From old AppEvent
    ConfigNext,    // Navigate config sections
    ConfigPrev,    // Navigate config sections
    ConfigEdit,    // Edit config value
    ConfigReset,   // Reset config to defaults
    ConfigExport,  // Export config
    ConfigImport,  // Import config
    
    // YouTube specific commands
    YoutubeClearCache,   // Clear YouTube cache
    YoutubeShowCache,    // Show cache statistics
    YoutubeDownload(String), // Download YouTube video without playing
    
    // Playlists
    PlaylistPlay { playlist_id: String, index: usize },
    PlaylistAdd { name: String },
    PlaylistDelete { playlist_id: String },
    PlaylistItemAdd { playlist_id: String, item: PlaylistItem },
    PlaylistItemDelete { playlist_id: String, item_id: String },
    PlaylistReload, // Force TUI to reload playlists from disk
    // Notify TUI of which playlist item is now playing
    PlaylistNowPlaying { playlist_id: String, item_id: String },
    PlaylistClearNowPlaying,
    
    // Internal application commands (from old AppEvent)
    UpdateState,
    Log(LogEntry),
    ExecuteCommand(String), // For executing command strings
}

impl Command {
    /// Convert a path/URL string to an Open command
    #[allow(dead_code)]
    pub fn open_media_from_path(path: String) -> Self {
        Command::Open(path)
    }
}

#[derive(Debug, Clone)]
pub struct CommandSuggestion {
    pub command: String,
    pub description: String,
    pub score: i64,
}

// Command metadata for suggestions and help
const COMMAND_DATA: &[(&str, &str)] = &[
    ("play", "Start playback"),
    ("pause", "Pause playback"),
    ("stop", "Stop playback"),
    ("toggle", "Toggle play/pause"),
    ("open", "Open media file or URL"),
    ("load", "Load media file or URL"),
    ("volume", "Set volume (0-100)"),
    ("vol", "Set volume (0-100)"),
    ("volumeup", "Increase volume"),
    ("volup", "Increase volume"),
    ("volumedown", "Decrease volume"),
    ("voldown", "Decrease volume"),
    ("mute", "Mute audio"),
    ("unmute", "Unmute audio"),
    ("seek", "Seek relative to current position"),
    ("seekto", "Seek to absolute position"),
    ("forward", "Seek forward"),
    ("backward", "Seek backward"),
    ("speed", "Set playback speed"),
    ("speedup", "Increase playback speed"),
    ("speeddown", "Decrease playback speed"),
    ("speedreset", "Reset playback speed to 1.0x"),
    ("fullscreen", "Enter fullscreen mode"),
    ("windowed", "Exit fullscreen mode"),
    ("togglefullscreen", "Toggle fullscreen mode"),
    ("loop", "Toggle loop mode"),
    ("toggleloop", "Toggle loop mode"),
    ("quit", "Quit application"),
    ("exit", "Exit application"),
    ("help", "Show help information"),
    ("connect", "Connect to VLC instance"),
    ("disconnect", "Disconnect from VLC"),
    ("test", "Test VLC connection"),
    ("config", "Show configuration"),
    ("save", "Save configuration"),
    ("reload", "Reload configuration"),
    ("export", "Export configuration to file"),
    ("import", "Import configuration from file"),
    ("reset", "Reset configuration to defaults"),
    ("ytcache", "Show YouTube cache statistics"),
    ("ytclear", "Clear YouTube cache"),
    ("ytdownload", "Download YouTube video"),
    ("youtube", "YouTube commands"),
    ("cache", "Cache management"),
    // Playlists
    ("pladd", "Add a new playlist: pladd <name>"),
    ("pldel", "Delete a playlist: pldel <playlist_id>"),
    ("plplay", "Play a playlist from index: plplay <playlist_id> [index]"),
    ("plitemadd", "Add item to playlist: plitemadd <playlist_id> <url> [name]"),
    ("plitemdel", "Delete item from playlist: plitemdel <playlist_id> <item_id>"),
    ("plreload", "Reload playlists from disk"),
];

impl CommandSuggestion {
    pub fn new(command: String, description: String, score: i64) -> Self {
        Self {
            command,
            description,
            score,
        }
    }
}

/// Get fuzzy search suggestions for commands
pub fn get_command_suggestions(input: &str) -> Vec<CommandSuggestion> {
    if input.is_empty() {
        return COMMAND_DATA.iter()
            .map(|(cmd, desc)| CommandSuggestion::new(cmd.to_string(), desc.to_string(), 1000))
            .collect();
    }

    let matcher = SkimMatcherV2::default();
    let input_lower = input.to_lowercase();
    let mut suggestions: Vec<CommandSuggestion> = Vec::new();

    // First pass: direct command matching
    for (cmd, desc) in COMMAND_DATA.iter() {
        let score = calculate_command_score(&input_lower, cmd, &matcher);
        if score > 0 {
            suggestions.push(CommandSuggestion::new(
                cmd.to_string(),
                desc.to_string(),
                score,
            ));
        }
    }

    // Second pass: alias matching
    for (cmd, desc) in COMMAND_DATA.iter() {
        if let Some(aliases) = get_command_aliases(cmd) {
            for alias in aliases {
                let alias_score = calculate_command_score(&input_lower, alias, &matcher);
                if alias_score > 0 {
                    // Add alias suggestion with slightly lower priority
                    suggestions.push(CommandSuggestion::new(
                        cmd.to_string(),
                        format!("{} (alias: {})", desc, alias),
                        alias_score - 100,
                    ));
                }
            }
        }
    }

    // Third pass: if we have very few results, try substring matching
    if suggestions.len() < 3 {
        for (cmd, desc) in COMMAND_DATA.iter() {
            // Skip if already added
            if suggestions.iter().any(|s| s.command == *cmd) {
                continue;
            }
            
            // Try character-by-character matching for very lenient fuzzy search
            if fuzzy_char_match(&input_lower, cmd) {
                suggestions.push(CommandSuggestion::new(
                    cmd.to_string(),
                    desc.to_string(),
                    100, // Lower score for fallback matches
                ));
            }
        }
    }

    // Remove duplicates and sort by score
    suggestions.sort_by(|a, b| b.score.cmp(&a.score));
    suggestions.dedup_by(|a, b| a.command == b.command);
    
    suggestions.truncate(10); // Limit to top 10 suggestions
    suggestions
}

fn fuzzy_char_match(input: &str, command: &str) -> bool {
    if input.is_empty() {
        return true;
    }
    
    let input_chars: Vec<char> = input.chars().collect();
    let command_chars: Vec<char> = command.chars().collect();
    
    let mut input_idx = 0;
    
    for &cmd_char in &command_chars {
        if input_idx < input_chars.len() && cmd_char == input_chars[input_idx] {
            input_idx += 1;
        }
    }
    
    // Return true if we matched all input characters in sequence
    input_idx == input_chars.len()
}

fn calculate_command_score(input: &str, command: &str, matcher: &SkimMatcherV2) -> i64 {
    // Exact match gets highest priority
    if input == command {
        return 10000;
    }
    
    // Prefix match gets high priority
    if command.starts_with(input) {
        return 5000 + (command.len() as i64 - input.len() as i64);
    }
    
    // Contains match gets medium priority
    if command.contains(input) {
        return 2000 + (command.len() as i64 - input.len() as i64);
    }
    
    // Fuzzy match using skim - be more lenient
    let fuzzy_score = matcher.fuzzy_match(command, input).unwrap_or(0);
    
    // For very short inputs (1-3 characters), be more lenient with fuzzy matching
    if input.len() <= 3 && fuzzy_score > 0 {
        return fuzzy_score.max(50); // Ensure minimum score for short inputs
    }
    
    fuzzy_score
}

fn get_command_aliases(command: &str) -> Option<Vec<&'static str>> {
    match command {
        "volume" => Some(vec!["vol", "sound"]),
        "volumeup" => Some(vec!["volup", "louder", "increase"]),
        "volumedown" => Some(vec!["voldown", "quieter", "decrease"]),
        "speedup" => Some(vec!["faster", "accelerate"]),
        "speeddown" => Some(vec!["slower", "decelerate"]),
        "speedreset" => Some(vec!["normal", "reset"]),
        "togglefullscreen" => Some(vec!["fs", "full"]),
        "toggleloop" => Some(vec!["loop", "repeat"]),
        "seekto" => Some(vec!["goto", "jump"]),
        "test" => Some(vec!["testconnection", "ping"]),
        "quit" => Some(vec!["q", "exit"]),
        "exit" => Some(vec!["q", "quit"]),
        _ => None,
    }
}

/// Parse a command string into a Command enum
pub fn parse_command(input: &str) -> Result<Command, String> {
    let trimmed = input.trim();
    
    if trimmed.is_empty() {
        return Err("Empty command".to_string());
    }

    let parts: Vec<&str> = trimmed.split_whitespace().collect();
    let cmd_str = parts[0].to_lowercase();

    match cmd_str.as_str() {
        "play" => Ok(Command::Play),
        "pause" => Ok(Command::Pause),
        "stop" => Ok(Command::Stop),
        "toggle" => Ok(Command::Toggle),
        
        "open" | "load" => {
            if parts.len() < 2 {
                return Err(format!("{} requires a file path or URL", cmd_str));
            }
            let path = parts[1..].join(" ");
            match cmd_str.as_str() {
                "open" => Ok(Command::Open(path)),
                "load" => Ok(Command::Load(path)),
                _ => unreachable!(),
            }
        },
        
        "volume" | "vol" => {
            if parts.len() < 2 {
                return Err("Volume requires a value (0-100)".to_string());
            }
            match parts[1].parse::<f64>() {
                Ok(vol) if (0.0..=100.0).contains(&vol) => Ok(Command::Volume(vol)),
                Ok(_) => Err("Volume must be between 0 and 100".to_string()),
                Err(_) => Err("Volume must be a number".to_string()),
            }
        },
        
        "volumeup" | "volup" => Ok(Command::VolumeUp),
        "volumedown" | "voldown" => Ok(Command::VolumeDown),
        "mute" => Ok(Command::Mute),
        "unmute" => Ok(Command::Unmute),
        
        "seek" => {
            if parts.len() < 2 {
                return Err("Seek requires a time value".to_string());
            }
            match parts[1].parse::<f64>() {
                Ok(time) => Ok(Command::Seek(time)),
                Err(_) => Err("Seek time must be a number".to_string()),
            }
        },
        
        "seekto" | "goto" | "jump" => {
            if parts.len() < 2 {
                return Err("SeekTo requires a time value".to_string());
            }
            match parts[1].parse::<f64>() {
                Ok(time) => Ok(Command::SeekTo(time)),
                Err(_) => Err("SeekTo time must be a number".to_string()),
            }
        },
        
        "forward" => {
            let time = if parts.len() > 1 {
                parts[1].parse::<f64>().unwrap_or(10.0)
            } else {
                10.0
            };
            Ok(Command::Forward(time))
        },
        
        "backward" => {
            let time = if parts.len() > 1 {
                parts[1].parse::<f64>().unwrap_or(10.0)
            } else {
                10.0
            };
            Ok(Command::Backward(time))
        },
        
        "speed" => {
            if parts.len() < 2 {
                return Err("Speed requires a value".to_string());
            }
            match parts[1].parse::<f64>() {
                Ok(speed) if speed > 0.0 => Ok(Command::Speed(speed)),
                Ok(_) => Err("Speed must be greater than 0".to_string()),
                Err(_) => Err("Speed must be a number".to_string()),
            }
        },
        
        "speedup" | "faster" => Ok(Command::SpeedUp),
        "speeddown" | "slower" => Ok(Command::SpeedDown),
        "speedreset" | "normal" | "reset" => Ok(Command::SpeedReset),
        "resetspeed" => Ok(Command::ResetSpeed),
        
        "fullscreen" => Ok(Command::Fullscreen),
        "windowed" => Ok(Command::Windowed),
        "togglefullscreen" | "fs" | "full" => Ok(Command::ToggleFullscreen),
        "loop" | "toggleloop" => Ok(Command::ToggleLoop),
        
        "quit" | "q" | "exit" => Ok(Command::Quit),
        "help" => Ok(Command::Help),
        "showhelp" => Ok(Command::ShowHelp),
        "hidehelp" => Ok(Command::HideHelp),
        "seekforward" => Ok(Command::SeekForward),
        "seekbackward" => Ok(Command::SeekBackward),
        
        "connect" => {
            if parts.len() < 2 {
                return Err("Connect requires a host".to_string());
            }
            let host = parts[1].to_string();
            let port = if parts.len() > 2 {
                match parts[2].parse::<u16>() {
                    Ok(p) => Some(p),
                    Err(_) => return Err("Port must be a valid number".to_string()),
                }
            } else {
                None
            };
            Ok(Command::Connect(host, port))
        },
        
        "disconnect" => Ok(Command::Disconnect),
        "test" | "testconnection" | "ping" => Ok(Command::TestConnection),
        "config" => Ok(Command::ShowConfig),
        "save" => Ok(Command::Save),
        "reload" => Ok(Command::Reload),
        "configreset" => Ok(Command::ConfigReset),
        
        "export" => {
            if parts.len() > 1 {
                let path = parts[1..].join(" ");
                Ok(Command::ExecuteCommand(format!("export_to {}", path)))
            } else {
                Ok(Command::ConfigExport)
            }
        },
        
        "import" => {
            if parts.len() > 1 {
                let path = parts[1..].join(" ");
                Ok(Command::ExecuteCommand(format!("import_from {}", path)))
            } else {
                Ok(Command::ConfigImport)
            }
        },
        
        // YouTube commands
        "ytcache" | "youtubecache" | "yt-cache" => Ok(Command::YoutubeShowCache),
        "ytclear" | "youtubeclear" | "yt-clear" => Ok(Command::YoutubeClearCache),
        "ytdownload" | "youtubedownload" | "yt-download" => {
            if parts.len() < 2 {
                return Err("YouTube download requires a URL".to_string());
            }
            let url = parts[1..].join(" ");
            Ok(Command::YoutubeDownload(url))
        },

        // Playlists
        "pladd" => {
            if parts.len() < 2 { return Err("Usage: pladd <name>".into()); }
            Ok(Command::PlaylistAdd { name: parts[1..].join(" ") })
        }
        "pldel" => {
            if parts.len() < 2 { return Err("Usage: pldel <playlist_id>".into()); }
            Ok(Command::PlaylistDelete { playlist_id: parts[1].to_string() })
        }
        "plplay" => {
            if parts.len() < 2 { return Err("Usage: plplay <playlist_id> [index]".into()); }
            let idx = if parts.len() > 2 { parts[2].parse::<usize>().unwrap_or(0) } else { 0 };
            Ok(Command::PlaylistPlay { playlist_id: parts[1].to_string(), index: idx })
        }
        "plitemadd" => {
            use crate::playlists::PlaylistItem;
            if parts.len() < 3 { return Err("Usage: plitemadd <playlist_id> <url> [name]".into()); }
            let playlist_id = parts[1].to_string();
            let url = parts[2].to_string();
            let name = if parts.len() > 3 { parts[3..].join(" ") } else { url.clone() };
            let item = PlaylistItem { name, id: String::new(), url, num_played: 0, duration: "".into(), time_added: 0 };
            Ok(Command::PlaylistItemAdd { playlist_id, item })
        }
        "plitemdel" => {
            if parts.len() < 3 { return Err("Usage: plitemdel <playlist_id> <item_id>".into()); }
            Ok(Command::PlaylistItemDelete { playlist_id: parts[1].to_string(), item_id: parts[2].to_string() })
        }
        "plreload" => Ok(Command::PlaylistReload),
        
        _ => Err(format!("Unknown command: {}", cmd_str)),
    }
}

/// Get all available commands for help display
#[allow(dead_code)]
pub fn get_all_commands() -> Vec<(String, String)> {
    COMMAND_DATA.iter()
        .map(|(cmd, desc)| (cmd.to_string(), desc.to_string()))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_commands() {
        assert_eq!(parse_command("play").unwrap(), Command::Play);
        assert_eq!(parse_command("pause").unwrap(), Command::Pause);
        assert_eq!(parse_command("STOP").unwrap(), Command::Stop);
    }

    #[test]
    fn test_parse_volume_commands() {
        assert_eq!(parse_command("volume 50").unwrap(), Command::Volume(50.0));
        assert_eq!(parse_command("vol 75").unwrap(), Command::Volume(75.0));
        assert!(parse_command("volume 150").is_err());
        assert!(parse_command("volume abc").is_err());
    }

    #[test]
    fn test_parse_file_commands() {
        assert_eq!(
            parse_command("open /path/to/file.mp4").unwrap(),
            Command::Open("/path/to/file.mp4".to_string())
        );
        assert_eq!(
            parse_command("load https://example.com/video.mp4").unwrap(),
            Command::Load("https://example.com/video.mp4".to_string())
        );
    }

    #[test]
    fn test_command_suggestions() {
        let suggestions = get_command_suggestions("pl");
        assert!(!suggestions.is_empty());
        assert!(suggestions.iter().any(|s| s.command == "play"));
    }

    #[test]
    fn test_quit_command_parsing() {
        // Test all variations of quit command
        let quit_commands = vec!["quit", "q", "exit", "QUIT", "EXIT"];
        
        for cmd in quit_commands {
            let result = parse_command(cmd);
            println!("Parsing '{}' -> {:?}", cmd, result);
            assert!(result.is_ok(), "Should parse '{}' successfully", cmd);
            assert_eq!(result.unwrap(), Command::Quit, "'{}' should parse to Command::Quit", cmd);
        }
    }

    #[test]
    fn test_single_suggestion_cases() {
        // Test cases that should return exactly one suggestion
        let test_cases = vec![
            ("disconn", "disconnect"),
            ("confi", "config"),
            ("relo", "reload"),
        ];
        
        for (input, expected) in test_cases {
            let suggestions = get_command_suggestions(input);
            println!("Input '{}' -> {} suggestions", input, suggestions.len());
            for (i, s) in suggestions.iter().enumerate() {
                println!("  {}: {} - {}", i, s.command, s.description);
            }
            
            // Should have at least one suggestion
            assert!(!suggestions.is_empty(), "Should have suggestions for '{}'", input);
            
            // The first suggestion should be the expected one
            assert_eq!(suggestions[0].command, expected, 
                "First suggestion for '{}' should be '{}'", input, expected);
        }
    }

    #[test]
    fn test_fuzzy_matching_edge_cases() {
        // Test the specific case mentioned by the user
        let suggestions = get_command_suggestions("pla");
        assert!(!suggestions.is_empty(), "Should have suggestions for 'pla'");
        assert!(suggestions.iter().any(|s| s.command == "play"), "Should suggest 'play' for 'pla'");
        
        // Test other partial matches
        let suggestions = get_command_suggestions("pa");
        assert!(suggestions.iter().any(|s| s.command == "pause"), "Should suggest 'pause' for 'pa'");
        
        let suggestions = get_command_suggestions("vo");
        assert!(suggestions.iter().any(|s| s.command == "volume"), "Should suggest 'volume' for 'vo'");
        
        // Test very short inputs
        let suggestions = get_command_suggestions("p");
        assert!(!suggestions.is_empty(), "Should have suggestions for 'p'");
        
        // Test character matching
        let suggestions = get_command_suggestions("stp");
        assert!(suggestions.iter().any(|s| s.command == "stop"), "Should suggest 'stop' for 'stp'");
    }
}