use {
    crate::{
        config::{
            Animations,
            context::Context,
            extractor::{Extractor, ExtractorError, bol, n32, opt, recover, str},
            parser::{DataType, ParseResult, Parser, UnexpectedDataType},
        },
        toml::{
            toml_span::{DespanExt, Span, Spanned},
            toml_value::Value,
        },
    },
    indexmap::IndexMap,
    thiserror::Error,
};

#[derive(Debug, Error)]
pub enum AnimationsParserError {
    #[error(transparent)]
    Expected(#[from] UnexpectedDataType),
    #[error(transparent)]
    Extract(#[from] ExtractorError),
}

pub struct AnimationsParser<'a>(pub &'a Context<'a>);

impl Parser for AnimationsParser<'_> {
    type Value = Animations;
    type Error = AnimationsParserError;
    const EXPECTED: &'static [DataType] = &[DataType::Table];

    fn parse_table(
        &mut self,
        span: Span,
        table: &IndexMap<Spanned<String>, Spanned<Value>>,
    ) -> ParseResult<Self> {
        let mut ext = Extractor::new(self.0, span, table);
        let (enabled, duration_ms, curve) = ext.extract((
            recover(opt(bol("enabled"))),
            recover(opt(n32("duration-ms"))),
            recover(opt(str("curve"))),
        ))?;
        Ok(Animations {
            enabled: enabled.despan(),
            duration_ms: duration_ms.despan(),
            curve: curve.despan().map(|s| s.to_string()),
        })
    }
}
