use std::{collections::HashMap, path::PathBuf, process};

use crate::types::grade::Grade;

use super::{deserialize_config_and_data, turn_string_to_class, turn_string_to_grade_type};

pub fn add(
    class: &String,
    grade_value: u16,
    grade_type: &String,
    comment: &Option<String>,
    unit: &Option<String>,
    raw_data_file: &PathBuf,
    raw_config_file: &PathBuf,
) {
    let (mut data_file, config_file) = deserialize_config_and_data(raw_data_file, raw_config_file);
    let class = turn_string_to_class(class, &config_file);
    let grade_type = turn_string_to_grade_type(grade_type, &config_file);

    let grade = Grade {
        grade_type: grade_type.name,
        value: grade_value,
        class,
        comment: comment.to_owned(),
        unit: if let Some(unit) = unit {
            unit.to_owned()
        } else {
            config_file.unit
        },
    };

    data_file
        .classes
        .entry(grade.class.class_type.clone())
        .or_insert(HashMap::new())
        .entry(grade.class.name.clone())
        .or_insert(HashMap::new())
        .entry(grade.grade_type.clone())
        .or_insert(Vec::new())
        .push(grade);

    if let Err(e) = data_file.to_ron_file(raw_data_file) {
        eprintln!("Error while writing the data file: {e}");
        process::exit(1);
    }
}
