use dlopen2::symbor::Library;
use gc_json_bridge::{GCJsonBridge, GCJsonCallbacks};
use gc_utils::testing::build_c_plugin;
use serde_json::Value;
use simple_logger::SimpleLogger;
use std::fs::File;
use std::io::BufReader;

fn setup_test_plugin() -> String {
    build_c_plugin("tests/test_plugin", "gc_json_bridge")
}

/// Builds and lauches a dll containing a test plugin
/// The assertions are done within the C plugin.
///
/// If one of the tests fails, might be usefull to rerun it again but adding a "return 0" before the assertion.
/// This will print the core logs to the terminal.
#[test]
fn test_json_bridge() {
    // Setup logging
    SimpleLogger::new().init().unwrap();
    let lib = setup_test_plugin();

    // Load the test plugin
    let lib = Library::open(lib).unwrap();
    let start_test_func = unsafe { lib.symbol::<unsafe extern "C" fn(GCJsonCallbacks) -> bool>("start_test") }.unwrap();

    println!("Test plugin loaded");
    // Load a json file
    let file_handle = File::open("tests/assets/asset_1.json").expect("Config file not found");
    let file_buffer = BufReader::new(file_handle);
    let parsed_json: Value = serde_json::from_reader(file_buffer).expect("Error while reading the config file");

    // Convert the json to GCJsonObject
    let gc_json_bridge = GCJsonBridge::new(&parsed_json);
    let callbacks = gc_json_bridge.gc_json_bridge_callbacks();

    unsafe { assert!(start_test_func(callbacks as GCJsonCallbacks)) };
}
