
use log::*;

use pest::Parser;

#[cfg(debug_assertions)]
const _GRAMMAR: &str = include_str!("generate.pest");

#[derive(Parser)]
#[grammar = "generate.pest"]
pub struct GenerateParser;

pub fn parse_generate(s: &str) -> Option<Vec<String>> {
    let pairs = GenerateParser::parse(Rule::file, s);

    if pairs.is_err() {
        return None;
    }

    let mut found = Vec::new();

    for pair in pairs.unwrap() {
        // A pair is a combination of the rule which matched and a span of input

        // A pair can be converted to an iterator of the tokens which make it up:
        for inner_pair in pair.into_inner() {
            let inner_span = inner_pair.clone().as_span();
            match inner_pair.as_rule() {
                Rule::filename => {
                    //println!("fname:  {}", inner_span.as_str());
                    // https://rust-lang-nursery.github.io/rust-clippy/v0.0.212/index.html#clone_double_ref
                    let s: String = inner_span.as_str().to_string();
                    //println!("filename: {}", s);
                    found.push(s);
                }
                Rule::EOI => (),
                e => {
                    error!("unreachable: {:?}", e);
                    unreachable!()
                }
            };
        }
    }
    if found.is_empty() {
        None
    } else {
        Some(found)
    }
}
