use crate::{RawParser, Event, FrontMatter, MarkdownExt, Options, Result, Share};
use serde_yaml;
use std::cell::RefCell;
use std::iter::Peekable;
use std::rc::Rc;

/// A wrapper for the [`RawParser`].
///
/// [`Parser`]: struct.RawParser.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Parser<'e> {
    parser: Peekable<RawParser<'e>>,
    frontmatter: Share<RefCell<Option<FrontMatter>>>,
}

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

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

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

impl<'e> MarkdownExt<Event<'e>> for Parser<'e> {
    fn frontmatter(&mut self) -> &mut Share<RefCell<Option<FrontMatter>>> {
        &mut self.frontmatter
    }
}
