use std::sync::OnceLock;

use serde::Deserialize;

use crate::{action::ActionConfig, DataLoadError};

const INTERACT_CONFIG_JSON: &str = "Interacts.json";
static EVENT_GRAPHS: OnceLock<Vec<EventGraphConfig>> = OnceLock::new();

#[derive(Deserialize, Debug)]
pub struct EventGraphConfig {
    pub event_id: u32,
    pub actions: Vec<ActionConfig>,
}

pub(crate) fn load_event_graphs(path: &str) -> Result<(), DataLoadError> {
    let data = std::fs::read_to_string(format!("{path}/{INTERACT_CONFIG_JSON}"))
        .map_err(|err| DataLoadError::IoError(err))?;

    let event_graphs = serde_json::from_str::<Vec<EventGraphConfig>>(&data)
        .map_err(|err| DataLoadError::FromJsonError(String::from("EventGraphCollection"), err))?;

    EVENT_GRAPHS.set(event_graphs).unwrap();
    Ok(())
}

pub fn interacts() -> std::slice::Iter<'static, EventGraphConfig> {
    EVENT_GRAPHS.get().unwrap().iter()
}
