// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright © 2024 Mike Robeson [dijksterhuis]

//! Filesystem utilities to check if an audio file at a
//! specific filesystem path will be supported by the Octatrack

use std::path::PathBuf;

use log::trace;

use super::{aiff, get_all_compatible_audio_specs, wav, AudioErrors, AudioSpec, SampleFormat, R};

/// Is the file at `path` a WAV file that is compatible with the Octatrack?
pub fn file_path_is_compat_wav(path: &PathBuf) -> R<bool> {
    trace!("Opening WAV file: path={path:#?}");
    let mut reader = wav::WavFile::open_read_buf(path)
        .map_err(wav::WavErrors::from)
        .map_err(AudioErrors::from)?;

    trace!("Opening WAV spec: path={path:#?}");
    let spec = wav::WavFile::get_spec(&mut reader)?;

    trace!("Creating AudioSpec: path={path:#?}");
    let audio_spec = AudioSpec {
        channels: spec.channels,
        sample_rate: spec.sample_rate,
        bit_depth: spec.bits_per_sample,
        format: SampleFormat::from(spec.sample_format),
    };

    trace!("Checking compatibility: spec={audio_spec:#?}");
    Ok(get_all_compatible_audio_specs().contains(&audio_spec))
}

/// Is the file at `path` an AIFF file that is compatible with the Octatrack?
pub fn file_path_is_compat_aiff(path: &PathBuf) -> R<bool> {
    trace!("Opening AIFF file: path={path:#?}");
    let mut reader = aiff::AiffFile::open_read_buf(path)?;

    trace!("Opening AIFF spec: path={path:#?}");
    let spec = aiff::AiffFile::get_spec(&mut reader);

    trace!("Creating AudioSpec: path={path:#?}");
    let audio_spec = AudioSpec {
        channels: spec.channels as u16,
        sample_rate: spec.sample_rate as u32,
        bit_depth: spec.comm_sample_size as u16,
        format: SampleFormat::from(spec.sample_format),
    };

    trace!("Checking compatibility: spec={audio_spec:#?}");
    Ok(get_all_compatible_audio_specs().contains(&audio_spec))
}
