#![cfg(test)]

use crate::parse::Parser;
use microformats_types::Document;
use std::path::PathBuf;
use url::Url;

pub type FixtureData = (String, String);

fn read_fixture(p: &str) -> FixtureData {
    let base_path = format!(
        "{}/../vendor/microformats-test/tests/{}",
        env!("CARGO_MANIFEST_DIR"),
        p
    );

    let pathbuf = PathBuf::from(base_path);

    let mut html_path = pathbuf.clone();
    html_path.set_extension("html");
    let mut json_path = pathbuf.clone();
    json_path.set_extension("json");

    let html = std::fs::read_to_string(html_path.clone())
        .unwrap_or_else(|_| panic!("Could not read the HTML from {:?}.", html_path));

    let json = std::fs::read_to_string(json_path.clone())
        .unwrap_or_else(|_| panic!("Could not read the JSON from {:?}.", json_path));

    (html, json)
}

fn check_fixture_for_parser(fixture_name: &str) {
    let root_url: Url = "http://example.com/".parse().unwrap();
    let (fixture_html, expected_mf2_json_string) = read_fixture(fixture_name);
    let expected_mf2_json_result = serde_json::from_str(&expected_mf2_json_string);

    let expected_mf2_document: Document = if let Ok(doc) = expected_mf2_json_result {
        doc
    } else {
        panic!(
            "Failed to generate expected document for the fixture {fixture_name} because {:#?}",
            expected_mf2_json_result.err()
        );
    };

    let parser = Parser::from_html(fixture_html).expect("The provided HTML could not be parsed.");
    let document_result = parser.into_document(Some(root_url));

    assert_eq!(
        document_result.as_ref().err(),
        None,
        "document parsed successfully"
    );
    let parsed_mf2_document = document_result.unwrap();

    similar_asserts::assert_serde_eq!(
        expected: serde_json::json!(expected_mf2_document),
        parsed: serde_json::json!(parsed_mf2_document),
        "checking if the expected matches the provided document"
    )
}

#[cfg(test)]
mod adhoc;

#[cfg(test)]
mod generated;
