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

//! Types and parsing of the attributes data for a project's sample slots.
//! Used in the [`crate::projects::ProjectFile`] type.
//!
//! NOTE: Sample slot attributes here refer to the non-'playback markers' data.
//! See [crate::markers::MarkersFile] for information on trim/loop/slice
//! settings for a project's sample slot.

/*
Example data:
[SAMPLE]\r\nTYPE=FLEX\r\nSLOT=001\r\nPATH=../AUDIO/flex.wav\r\nTRIM_BARSx100=173\r\nTSMODE=2\r\nLOOPMODE=1\r\nGAIN=48\r\nTRIGQUANTIZATION=-1\r\n[/SAMPLE]
-----

[SAMPLE]
TYPE=FLEX
SLOT=001
PATH=../AUDIO/flex.wav
TRIM_BARSx100=173
TSMODE=2
LOOPMODE=1
GAIN=48
TRIGQUANTIZATION=-1
[/SAMPLE]
*/

use crate::{
    projects::{parse_hashmap_string_value, FromHashMap},
    IsDefault, LoopMode, OptionEnumValueConvert, OtToolsIoErrors, RBoxErr, TimestrechMode,
    TrigQuantizationMode,
};
use itertools::Itertools;
use serde::de::{self, Deserializer, MapAccess, Visitor};
use serde::{Deserialize, Serialize};
use serde_big_array::Array;
use std::fmt;
use std::{collections::HashMap, path::PathBuf, str::FromStr};

/// A sample slot's global playback settings -- trig quantization, bpm,
/// timestrech mode ... anything applied to the sample globally .
/// The Octatrack only stores data when an audio file has been assigned to a sample slot.
///
/// NOTE: On the naming for this -- the Octatrack manual specifically refers to
/// > SAVE SAMPLE SETTINGS will save the trim, slice and attribute settings in a
/// > separate file and link it to the sample currently being edited.
/// > -- page 87
///
/// So ... these are the Slot ATTRIBUTES which are saved to a settings file.
#[derive(Serialize, PartialEq, Debug, Clone, Eq, Hash)]
pub struct SlotAttributes {
    /// Type of sample: STATIC or FLEX
    pub slot_type: SlotType,

    /// String ID Number of the slot the sample is assigned to e.g. 001, 002, 003...
    /// Maximum of 128 entries for STATIC sample slots, but can be up to 136 for flex
    /// slots as there are 8 recorders + 128 flex slots.
    pub slot_id: u8,

    /// Relative path to the file on the card from the project directory.
    ///
    /// Recording buffer flex slots by default have an empty path attribute,
    /// which basically means 'no path'. In idiomatic rust that's an option.
    pub path: Option<PathBuf>,

    /// Current `TimestrechModes` setting for the specific slot. Example: `TSMODE=2`
    /// See [TimestrechMode].
    pub timestrech_mode: TimestrechMode,

    /// Current `LoopMode` setting for the specific slot.
    /// See [LoopMode].
    pub loop_mode: LoopMode,

    /// Current `TrigQuantizationModes` setting for this specific slot.
    /// This is not used for recording buffer 'flex' tracks.
    /// See [TrigQuantizationMode].
    pub trig_quantization_mode: TrigQuantizationMode,

    /// Sample gain. 48 is default as per sample attributes file. maximum 96, minimum 0.
    pub gain: u8,

    /// BPM of the sample in this slot. The stored representation is the 'real' bpm (float to 2
    /// decimal places) multiplied by 24.
    /// Default value is 2880 (120 BPM).
    /// Max value is 7200 (300 BPM).
    /// Min value is 720 (30 BPM).
    pub bpm: u16,
}

#[allow(clippy::too_many_arguments)] // not my fault there's a bunch of inputs for this...
impl SlotAttributes {
    pub fn new(
        slot_type: SlotType,
        slot_id: u8,
        path: Option<PathBuf>,
        timestretch_mode: Option<TimestrechMode>,
        loop_mode: Option<LoopMode>,
        trig_quantization_mode: Option<TrigQuantizationMode>,
        gain: Option<u8>,
        bpm: Option<u16>,
    ) -> RBoxErr<Self> {
        if let Some(tempo) = bpm {
            if !(720..=7200).contains(&tempo) {
                return Err(crate::samples::SampleSettingsErrors::TempoOutOfBounds.into());
            }
        }
        if let Some(amp) = gain {
            if !(24..=120).contains(&amp) {
                return Err(crate::samples::SampleSettingsErrors::GainOutOfBounds.into());
            }
        }

        Ok(Self {
            slot_type,
            slot_id,
            path,
            timestrech_mode: timestretch_mode.unwrap_or_default(),
            loop_mode: loop_mode.unwrap_or_default(),
            trig_quantization_mode: trig_quantization_mode.unwrap_or_default(),
            gain: gain.unwrap_or(72),
            bpm: bpm.unwrap_or(2880),
        })
    }
}

fn parse_id(hmap: &HashMap<String, String>) -> RBoxErr<u8> {
    let x = parse_hashmap_string_value::<u8>(hmap, "slot", None)?;
    Ok(x)
}

fn parse_loop_mode(hmap: &HashMap<String, String>) -> RBoxErr<LoopMode> {
    // TODO: generic trait definition instead of bounded trait (can't remember the name for the
    //       technique i used here but i know what i mean) -- allow for string value return etc
    let default = LoopMode::default().value()?;
    let default_str = format!["{default}"];

    let x = parse_hashmap_string_value::<u32>(hmap, "loopmode", Some(default_str.as_str()))
        .unwrap_or(default);
    LoopMode::from_value(&x)
}

fn parse_tstrech_mode(hmap: &HashMap<String, String>) -> RBoxErr<TimestrechMode> {
    // TODO: generic trait definition instead of bounded trait (can't remember the name for the
    //       technique i used here but i know what i mean) -- allow for string value return etc
    let default = TimestrechMode::default().value()?;
    let default_str = format!["{default}"];

    let x = parse_hashmap_string_value::<u32>(hmap, "tsmode", Some(default_str.as_str()))
        .unwrap_or(default);
    TimestrechMode::from_value(&x)
}

fn parse_trig_quantize_mode(hmap: &HashMap<String, String>) -> RBoxErr<TrigQuantizationMode> {
    // TODO: generic trait definition instead of bounded trait (can't remember the name for the
    //       technique i used here but i know what i mean) -- allow for string value return etc
    let default = TrigQuantizationMode::default().value()?;
    let default_str = format!["{default}"];
    let x = parse_hashmap_string_value::<u32>(hmap, "trigquantization", Some(default_str.as_str()))
        .unwrap_or(default);
    TrigQuantizationMode::from_value(&x)
}

fn parse_gain(hmap: &HashMap<String, String>) -> RBoxErr<u8> {
    let x = parse_hashmap_string_value::<u8>(hmap, "gain", Some("72")).unwrap_or(72_u8);
    Ok(x)
}

fn parse_tempo(hmap: &HashMap<String, String>) -> RBoxErr<u16> {
    let x = parse_hashmap_string_value::<u16>(hmap, "bpmx24", Some("2880")).unwrap_or(2880_u16);
    Ok(x)
}

// cannot use FromProjectStringData because it expects a lone Self result, rather than a Vec.
impl FromHashMap for SlotAttributes {
    type A = String;
    type B = String;
    type T = SlotAttributes;

    fn from_hashmap(hmap: &HashMap<Self::A, Self::B>) -> RBoxErr<Self::T> {
        let slot_id = parse_id(hmap)?;
        let sample_slot_type = hmap
            .get("type")
            .ok_or(OtToolsIoErrors::ProjectSampleSlotParsingError)?
            .to_string();
        let slot_type = SlotType::from_value(&sample_slot_type)?;
        let path = PathBuf::from_str(
            hmap.get("path")
                .ok_or(OtToolsIoErrors::ProjectSampleSlotParsingError)?,
        )?;
        let loop_mode = parse_loop_mode(hmap)?;
        let timestrech_mode = parse_tstrech_mode(hmap)?;
        let trig_quantization_mode = parse_trig_quantize_mode(hmap)?;
        let gain = parse_gain(hmap)?;
        let bpm = parse_tempo(hmap)?;

        let sample_struct = Self {
            slot_type,
            slot_id,
            path: if path != PathBuf::from("") {
                Some(path)
            } else {
                None
            },
            timestrech_mode,
            loop_mode,
            trig_quantization_mode,
            gain,
            bpm,
        };

        Ok(sample_struct)
    }
}

impl FromStr for SlotAttributes {
    type Err = Box<dyn std::error::Error>;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let k_v: Vec<Vec<&str>> = s
            .strip_prefix("\r\n\r\n[SAMPLE]\r\n")
            .ok_or(OtToolsIoErrors::ProjectSampleSlotParsingError)?
            .strip_suffix("\r\n")
            .ok_or(OtToolsIoErrors::ProjectSampleSlotParsingError)?
            .split("\r\n")
            .map(|x: &str| x.split('=').collect_vec())
            .filter(|x: &Vec<&str>| x.len() == 2)
            .collect_vec();

        let mut hmap: HashMap<String, String> = HashMap::new();
        for key_value_pair in k_v {
            hmap.insert(
                key_value_pair[0].to_string().to_lowercase(),
                key_value_pair[1].to_string(),
            );
        }

        let sample_struct = SlotAttributes::from_hashmap(&hmap)?;
        Ok(sample_struct)
    }
}

impl fmt::Display for SlotAttributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let mut s = "[SAMPLE]\r\n".to_string();
        s.push_str(format!("TYPE={}", self.slot_type.value().map_err(|_| fmt::Error)?).as_str());
        s.push_str("\r\n");
        // NOTE: Slot ID data is always prefixed with leading zeros
        s.push_str(format!("SLOT={:0>3}", self.slot_id).as_str());
        s.push_str("\r\n");
        // NOTE: Handle recording buffers having empty paths
        if let Some(path) = &self.path {
            /*
            HACK: Remove escape characters from the path string.

            A path like `my\file.wav` ends up like `my\\\\[...loads more \ chars...]\\\file.wav`.
            The Octatrack will attempt to load the project and then a catastrophic error message pops up.
            Helpfully, it will have made changes to the `project.work` file already which means you
            have to manually fix it yourself.

            This looks like some recursive injection of escape characters during parsing of the PATH field.
            Basically ... don't use the `\` escape character in path names!
            */
            s.push_str(
                format!("PATH={path:#?}")
                    .replace('"', "") // should not have quotes on PATH fields
                    .replace("\\", "") // ^ need to remove escape chars (`\`)
                    .as_str(),
            );
        } else {
            s.push_str("PATH=");
        }
        s.push_str("\r\n");
        s.push_str(format!("BPMx24={}", self.bpm).as_str());
        s.push_str("\r\n");
        s.push_str(
            format!(
                "TSMODE={}",
                self.timestrech_mode.value().map_err(|_| fmt::Error)?
            )
            .as_str(),
        );
        s.push_str("\r\n");
        s.push_str(
            format!(
                "LOOPMODE={}",
                self.loop_mode.value().map_err(|_| fmt::Error)?
            )
            .as_str(),
        );
        s.push_str("\r\n");
        s.push_str(format!("GAIN={}", self.gain).as_str());
        s.push_str("\r\n");
        s.push_str(
            format!(
                "TRIGQUANTIZATION={}",
                self.trig_quantization_mode
                    .value()
                    .map_err(|_| fmt::Error)?
            )
            .as_str(),
        );
        s.push_str("\r\n[/SAMPLE]");
        write!(f, "{s:#}")
    }
}

// YAML/JSON Deserialization for Sample Slot
// we can get away with just defining map deserialization for YAML/JSON.
// `ToString`/`FromStr` implementations are currently used for the actual data file.
impl<'de> Deserialize<'de> for SlotAttributes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            SlotType,
            SlotId,
            Path,
            Timestretch,
            Loop,
            Quant,
            Gain,
            Bpm,
        }

        // TODO: FIELDS_MAP: Tuple array
        const FIELDS: &[&str] = &[
            "slot_type",
            "slot_id",
            "path",
            "timestrech_mode",
            "loop_mode",
            "trig_quantization_mode",
            "gain",
            "bpm",
        ];

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct FieldVisitor;

                impl Visitor<'_> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str(
                            FIELDS
                                .iter()
                                .map(|x| format!["`{x}`"])
                                .collect::<Vec<_>>()
                                .join(" or ")
                                .as_str(),
                        )
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            "slot_type" => Ok(Field::SlotType),
                            "slot_id" => Ok(Field::SlotId),
                            "path" => Ok(Field::Path),
                            "timestrech_mode" => Ok(Field::Timestretch),
                            "loop_mode" => Ok(Field::Loop),
                            "trig_quantization_mode" => Ok(Field::Quant),
                            "gain" => Ok(Field::Gain),
                            "bpm" => Ok(Field::Bpm),
                            _ => Err(de::Error::unknown_field(value, FIELDS)),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct SlotAttributesVisitor;

        impl<'de> Visitor<'de> for SlotAttributesVisitor {
            type Value = SlotAttributes;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct SlotAttributes")
            }

            fn visit_map<V>(self, mut map: V) -> Result<SlotAttributes, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut slot_type = None;
                let mut slot_id = None;
                let mut path = None;
                let mut timestretch_mode = None;
                let mut loop_mode = None;
                let mut trig_quantization_mode = None;
                let mut gain = None;
                let mut bpm = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::SlotType => {
                            if slot_type.is_some() {
                                return Err(de::Error::duplicate_field("slot_type"));
                            }
                            slot_type = Some(map.next_value::<SlotType>()?);
                        }
                        Field::SlotId => {
                            if slot_id.is_some() {
                                return Err(de::Error::duplicate_field("slot_id"));
                            }
                            slot_id = Some(map.next_value::<u8>()?);
                        }
                        Field::Path => {
                            if path.is_some() {
                                return Err(de::Error::duplicate_field("path"));
                            }
                            path = Some(map.next_value::<PathBuf>()?);
                        }
                        Field::Timestretch => {
                            if timestretch_mode.is_some() {
                                return Err(de::Error::duplicate_field("timestretch_mode"));
                            }
                            timestretch_mode = Some(map.next_value::<TimestrechMode>()?);
                        }
                        Field::Loop => {
                            if loop_mode.is_some() {
                                return Err(de::Error::duplicate_field("loop_mode"));
                            }
                            loop_mode = Some(map.next_value::<LoopMode>()?);
                        }
                        Field::Quant => {
                            if trig_quantization_mode.is_some() {
                                return Err(de::Error::duplicate_field("trig_quantization_mode"));
                            }
                            trig_quantization_mode =
                                Some(map.next_value::<TrigQuantizationMode>()?);
                        }
                        Field::Gain => {
                            if gain.is_some() {
                                return Err(de::Error::duplicate_field("gain"));
                            }
                            gain = Some(map.next_value::<u8>()?);
                        }
                        Field::Bpm => {
                            if bpm.is_some() {
                                return Err(de::Error::duplicate_field("bpm"));
                            }
                            bpm = Some(map.next_value::<u16>()?);
                        }
                    }
                }

                let slot = SlotAttributes {
                    slot_type: slot_type.ok_or_else(|| de::Error::missing_field("slot_type"))?,
                    slot_id: slot_id.ok_or_else(|| de::Error::missing_field("slot_type"))?,
                    path, // allowed to be missing to handle recording buffer empty paths
                    timestrech_mode: timestretch_mode
                        .ok_or_else(|| de::Error::missing_field("trimstretch_mode"))?,
                    loop_mode: loop_mode.ok_or_else(|| de::Error::missing_field("loop_mode"))?,
                    trig_quantization_mode: trig_quantization_mode
                        .ok_or_else(|| de::Error::missing_field("trig_quantization_mode"))?,
                    gain: gain.ok_or_else(|| de::Error::missing_field("gain"))?,
                    bpm: bpm.ok_or_else(|| de::Error::missing_field("bpm"))?,
                };

                Ok(slot)
            }
        }

        deserializer.deserialize_struct("SampleSlot", FIELDS, SlotAttributesVisitor)
    }
}

/// Container type for all sample slots.
///
/// The `project.*` data files store all sample slots together in a single 1-indexed array.
/// This tends to lead to a lot of additional yak-shaving when interacting with sample slots.
/// So this type models the octatrack's UI, displaying slots in 2x arrays: Flex and Static.
/// These individual arrays are 0-indexed (easier lookups within for loops etc), but the
/// slots themselves retain their 1-indexed slot IDs.
///
/// NOTE: This type only includes the ATTRIBUTE data for slots. Markers data is
/// stored separately in [crate::markers::MarkersFile].
///
/// NOTE: I'm aware of the dangerous naming here -- `SlotX` versus `SlotsX` ...
/// lean into the type system to stop you from using the wrong one! `SlotsX` is
/// a container, while `SlotX` is the single slot with it's data (naming things
/// is hard, okay).
///
/// To create a new [SlotsAttributes] instance, start with a mutable default
/// as it will generate the recording buffer flex slots for you!
/// ```rust
/// # use ot_tools_io::projects::slots::SlotType;
/// # use ot_tools_io::projects::slots::SlotsAttributes;
///
/// let mut slots = SlotsAttributes::default();
/// for i in (128..=135_usize) {
///    let s = slots.flex_slots[i].clone();
///    assert_eq!(s.unwrap().slot_type, SlotType::Flex)
/// }
/// ```
#[derive(Eq, PartialEq, Clone, Debug, Serialize)]
pub struct SlotsAttributes {
    pub static_slots: Array<Option<SlotAttributes>, 128>,
    pub flex_slots: Array<Option<SlotAttributes>, 136>,
}

// YAML/JSON Deserialization for Sample Slots
// we can get away with just defining map deserialization for YAML/JSON.
// `ToString`/`FromStr` implementations are currently used for the actual data file.
impl<'de> Deserialize<'de> for SlotsAttributes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            Static,
            Flex,
        }

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct FieldVisitor;

                impl Visitor<'_> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str("`static_slots` or `flex_slots`")
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            "static_slots" => Ok(Field::Static),
                            "flex_slots" => Ok(Field::Flex),
                            _ => Err(de::Error::unknown_field(value, FIELDS)),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct SampleSlotsVisitor;

        impl<'de> Visitor<'de> for SampleSlotsVisitor {
            type Value = SlotsAttributes;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct SampleSlots")
            }

            fn visit_unit<E>(self) -> Result<SlotsAttributes, E> {
                Ok(SlotsAttributes::default())
            }
            fn visit_map<V>(self, mut map: V) -> Result<SlotsAttributes, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut static_slots = None;
                let mut flex_slots = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Static => {
                            if static_slots.is_some() {
                                return Err(de::Error::duplicate_field("static_slots"));
                            }
                            static_slots =
                                Some(map.next_value::<Array<Option<SlotAttributes>, 128>>()?);
                        }
                        Field::Flex => {
                            if flex_slots.is_some() {
                                return Err(de::Error::duplicate_field("flex_slots"));
                            }
                            flex_slots =
                                Some(map.next_value::<Array<Option<SlotAttributes>, 136>>()?);
                        }
                    }
                }
                let s_slots =
                    static_slots.ok_or_else(|| de::Error::missing_field("static_slots"))?;

                let f_slots = flex_slots.ok_or_else(|| de::Error::missing_field("flex_slots"))?;

                let slots = SlotsAttributes {
                    static_slots: s_slots,
                    flex_slots: f_slots,
                };

                Ok(slots)
            }
        }

        const FIELDS: &[&str] = &["static_slots", "flex_slots"];
        deserializer.deserialize_struct("SampleSlots", FIELDS, SampleSlotsVisitor)
    }
}

/// Helper function, no public
fn flex_slot_default_case_switch(i: usize) -> Option<SlotAttributes> {
    if i <= 127 {
        None
    } else {
        Some(SlotAttributes {
            slot_type: SlotType::Flex,
            // WARN: i is a 0-indexed iterable, slot IDs need to be 1-indexed!
            slot_id: i as u8 + 1,
            path: None,
            timestrech_mode: TimestrechMode::default(),
            loop_mode: LoopMode::default(),
            trig_quantization_mode: TrigQuantizationMode::default(),
            gain: 72,
            bpm: 2880,
        })
    }
}

impl Default for SlotsAttributes {
    fn default() -> Self {
        Self {
            static_slots: Array(std::array::from_fn(|_| None)),
            flex_slots: Array(std::array::from_fn(flex_slot_default_case_switch)),
        }
    }
}

impl IsDefault for SlotsAttributes {
    fn is_default(&self) -> bool {
        *self == SlotsAttributes::default()
    }
}

impl FromStr for SlotsAttributes {
    type Err = OtToolsIoErrors;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // TODO: option plain unwrap
        let footer_stripped = s
            .strip_suffix("\r\n\r\n############################\r\n\r\n")
            .ok_or(OtToolsIoErrors::ProjectSampleSlotParsingError)?;

        let data_window: Vec<&str> = footer_stripped
            .split("############################\r\n# Samples\r\n############################")
            .collect();

        let mut samples_string: Vec<&str> = data_window[1].split("[/SAMPLE]").collect();
        // last one is always a blank string.
        samples_string.pop();

        // mutate from default as we always need recording buffers populated
        let mut slots = Self::default();

        for s in &samples_string {
            // need zero indexing to insert slots into arrays
            let slot = SlotAttributes::from_str(s)
                .map_err(|_| OtToolsIoErrors::ProjectSampleSlotParsingError)?;
            let zero_indexed_id = slot.slot_id as usize - 1;
            match slot.slot_type {
                SlotType::Static => {
                    slots.static_slots[zero_indexed_id] = Some(slot);
                }
                SlotType::Flex => {
                    slots.flex_slots[zero_indexed_id] = Some(slot);
                }
            }
        }

        Ok(slots)
    }
}

impl fmt::Display for SlotsAttributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let mut string_slots: String = "".to_string();

        let slots = vec![self.static_slots.to_vec(), self.flex_slots.to_vec()];

        let slots_concat = itertools::concat(slots).into_iter().flatten();

        for slot in slots_concat {
            string_slots.push_str(&slot.to_string());
            string_slots.push_str("\r\n\r\n");
        }
        string_slots = string_slots
            .strip_suffix("\r\n\r\n")
            .ok_or(fmt::Error)?
            .to_string();
        write!(f, "{string_slots:#}")
    }
}

#[cfg(test)]
#[allow(unused_imports)]
mod test {

    #[test]
    fn parse_id_001_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "001".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(1, slot_id.unwrap());
    }

    #[test]
    fn parse_id_1_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "1".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(1, slot_id.unwrap());
    }

    #[test]
    fn parse_id_127_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "127".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(127, slot_id.unwrap());
    }

    #[test]
    fn parse_id_099_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "099".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(99, slot_id.unwrap());
    }

    #[test]
    fn parse_id_010_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "010".to_string());

        let slot_id = crate::projects::slots::parse_id(&hmap);

        assert_eq!(10, slot_id.unwrap());
    }

    #[test]
    fn test_parse_id_err_bad_value_type_err() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("slot".to_string(), "AAAA".to_string());
        let slot_id = crate::projects::slots::parse_id(&hmap);
        assert!(slot_id.is_err());
    }

    #[test]
    fn test_parse_tempo_correct_default() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "2880".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(2880_u16, r.unwrap());
    }

    #[test]
    fn test_parse_tempo_correct_min() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "720".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(720_u16, r.unwrap());
    }

    #[test]
    fn test_parse_tempo_correct_max() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "7200".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(7200_u16, r.unwrap());
    }

    #[test]
    fn test_parse_tempo_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("bpmx24".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_tempo(&hmap);
        assert_eq!(r.unwrap(), 2880_u16);
    }

    #[test]
    fn test_parse_gain_correct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("gain".to_string(), "72".to_string());
        let r = crate::projects::slots::parse_gain(&hmap);
        assert_eq!(72, r.unwrap());
    }

    #[test]
    fn test_parse_gain_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("gain".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_gain(&hmap);
        assert_eq!(r.unwrap(), 72_u8);
    }

    #[test]
    fn test_parse_loop_mode_correct_off() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "0".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::LoopMode::Off);
    }

    #[test]
    fn test_parse_loop_mode_correct_normal() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "1".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::LoopMode::Normal);
    }

    #[test]
    fn test_parse_loop_mode_correct_pingpong() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "2".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::LoopMode::PingPong);
    }

    #[test]
    fn test_parse_loop_mode_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("loopmode".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_loop_mode(&hmap);
        assert_eq!(r.unwrap(), crate::LoopMode::default());
    }

    #[test]
    fn test_parse_tstretch_correct_off() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "0".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(crate::TimestrechMode::Off, r.unwrap());
    }

    #[test]
    fn test_parse_tstretch_correct_normal() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "2".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(crate::TimestrechMode::Normal, r.unwrap());
    }

    #[test]
    fn test_parse_tstretch_correct_beat() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "3".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(crate::TimestrechMode::Beat, r.unwrap());
    }

    #[test]
    fn test_parse_tstretch_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("tsmode".to_string(), "AAAFSFSFSSFfssafAA".to_string());
        let r = crate::projects::slots::parse_tstrech_mode(&hmap);
        assert_eq!(r.unwrap(), crate::TimestrechMode::default());
    }

    #[test]
    fn test_parse_tquantize_correct_off() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "255".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::TrigQuantizationMode::Direct, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_direct() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "0".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::TrigQuantizationMode::PatternLength, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_onestep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "1".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::TrigQuantizationMode::OneStep, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_twostep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "2".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::TrigQuantizationMode::TwoSteps, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_threestep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "3".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::TrigQuantizationMode::ThreeSteps, r.unwrap());
    }

    #[test]
    fn test_parse_tquantize_correct_fourstep() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert("trigquantization".to_string(), "4".to_string());
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(crate::TrigQuantizationMode::FourSteps, r.unwrap());
    }

    // i'm not going to test every single option. we do that already elsewhere.

    #[test]
    fn test_parse_tquantize_bad_value_type_default_return() {
        let mut hmap = std::collections::HashMap::new();
        hmap.insert(
            "trigquantization".to_string(),
            "AAAFSFSFSSFfssafAA".to_string(),
        );
        let r = crate::projects::slots::parse_trig_quantize_mode(&hmap);
        assert_eq!(r.unwrap(), crate::TrigQuantizationMode::default());
    }
}

/// Slot's machine type (cannot access flex samples for a static machine etc).
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Eq, Hash)]
pub enum SlotType {
    /// Static machine slot
    Static,

    /// Flex machine slot
    Flex,
}

impl SlotType {
    pub fn other(&self) -> Self {
        match self {
            Self::Static => Self::Flex,
            Self::Flex => Self::Static,
        }
    }
}

impl OptionEnumValueConvert<String> for SlotType {
    fn from_value(v: &String) -> RBoxErr<Self> {
        match v.to_ascii_uppercase().as_str() {
            "STATIC" => Ok(SlotType::Static),
            "FLEX" => Ok(SlotType::Flex),
            _ => Err(OtToolsIoErrors::NoMatchingOptionEnumValue.into()),
        }
    }

    fn value(&self) -> RBoxErr<String> {
        match self {
            SlotType::Static => Ok("STATIC".to_string()),
            SlotType::Flex => Ok("FLEX".to_string()),
        }
    }
}

#[cfg(test)]
mod test_spec {
    mod value {
        // NOTE: @dijksterhuis: have to import the trait to use it
        use crate::projects::slots::SlotType;
        use crate::OptionEnumValueConvert;

        #[test]
        fn test_static() {
            assert_eq!(SlotType::Static.value().unwrap(), "STATIC");
        }
        #[test]
        fn test_flex() {
            assert_eq!(SlotType::Flex.value().unwrap(), "FLEX");
        }
    }

    mod from_value {
        use crate::projects::slots::SlotType;
        use crate::OptionEnumValueConvert;

        #[test]
        fn test_error() {
            assert!(SlotType::from_value(&"SOME INCORRECT STRING".to_string()).is_err(),);
        }

        #[test]
        fn test_static_upper() {
            assert_eq!(
                SlotType::Static,
                SlotType::from_value(&"STATIC".to_string()).unwrap(),
            );
        }

        #[test]
        fn test_static_lower() {
            assert_eq!(
                SlotType::Static,
                SlotType::from_value(&"static".to_string()).unwrap(),
            );
        }

        #[test]
        fn test_flex_upper() {
            assert_eq!(
                SlotType::Flex,
                SlotType::from_value(&"FLEX".to_string()).unwrap(),
            );
        }

        #[test]
        fn test_flex_lower() {
            assert_eq!(
                SlotType::Flex,
                SlotType::from_value(&"flex".to_string()).unwrap(),
            );
        }
    }
}
