use std::{fs, io::Read, path::PathBuf};

use lunar_lib::{
    config::Config,
    paths::{config_dir, recurse_list_from_root},
};

use crate::{config::CommonConfig, media_container::ContainerFormat};

// Config trait
impl Config for CommonConfig {
    const CONFIG_FILE_NAME: &'static str = "common";

    fn config_dir() -> PathBuf {
        config_dir()
    }
}

// Accessors
impl CommonConfig {
    /// Returns all supported audio files from the configured source directories
    #[must_use]
    pub(crate) fn get_source_files(&self) -> Vec<PathBuf> {
        self.main
            .source_directories
            .iter()
            .flat_map(|path| -> Vec<PathBuf> {
                recurse_list_from_root(path, false)
                    .filter_map(|f| {
                        let mut file = fs::File::open(&f).ok()?;
                        let mut buf = [0_u8; 16];
                        file.read_exact(&mut buf).ok()?;
                        ContainerFormat::from_buf(&buf)?;
                        Some(f)
                    })
                    .collect()
            })
            .collect()
    }
}
