use crate::MarkdownExt;
use equt_md as markdown;
use equt_md_error::Result;
use equt_md_frontmatter::FrontMatter;
use serde_yaml;
use std::iter::Peekable;

/// A wrapper for the original [`Parser`].
///
/// [`Parser`]: https://docs.rs/equt-md/*/equt_md/struct.Parser.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Parser<'e> {
    parser: Peekable<markdown::Parser<'e>>,
    frontmatter: Option<FrontMatter>,
}

impl<'e> Parser<'e> {
    /// Create a **full-feature** parser.
    pub fn new(text: &'e str) -> Result<Parser<'e>> {
        let mut parser = markdown::Parser::new_ext(text, markdown::Options::all()).peekable();
        return if let Some(markdown::Event::Frontmatter(s)) = parser.peek() {
            let fm: FrontMatter = serde_yaml::from_str(s)?;
            parser.next();
            Ok(Parser {
                parser,
                frontmatter: Some(fm),
            })
        } else {
            Ok(Parser {
                parser,
                frontmatter: None,
            })
        };
    }
}

impl<'e> Iterator for Parser<'e> {
    type Item = markdown::Event<'e>;

    fn next(&mut self) -> Option<Self::Item> {
        self.parser.next()
    }
}

impl<'e> MarkdownExt<markdown::Event<'e>> for Parser<'e> {
    fn frontmatter(&mut self) -> Option<FrontMatter> {
        std::mem::replace(&mut self.frontmatter, None)
    }
}
