mod model;
mod routes;
mod types;

use std::{fs::{metadata, File, read_dir}, path::Path, io::BufReader};

use log::{warn, trace};
pub use model::*;
pub use types::*;
pub use routes::init_routes;

pub fn load_data(data_dir_path: &str) {
  if Path::new(data_dir_path).exists() {
    let meta = metadata(data_dir_path).unwrap();
    if meta.is_dir() {
      let spells_dir_path = format!("{}/spells", data_dir_path);
      if Path::new(&spells_dir_path).exists() {
        let meta = metadata(&spells_dir_path).unwrap();
        if meta.is_dir() {
          for entry in read_dir(&spells_dir_path).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            if path.is_file() {
              let file = File::open(path).unwrap();
              let reader = BufReader::new(file);
              let result: Result<Vec<Spell>, serde_json::Error> = serde_json::from_reader(reader);
              match result {
                Ok(spells) => {
                  for spell in spells {
                    let mut filters = QueryFilters::default();
                    filters.by_name = Some(spell.name.clone());
                    match QuerySpell::get_all(&filters, 100, 1) {
                      Ok(spells) => {
                        if spells.len() > 0 {
                          trace!("Spell '{}' already exists", spell.name);
                          continue;
                        }
                      },
                      Err(err) => {
                        warn!("Error checking if spell '{}' exists: {}", spell.name, err);
                        continue;
                      }
                    };
                    let spell = InsertSpell::insert(spell.into()).unwrap();
                    trace!("Inserted spell: {}", spell.name);
                  }
                },
                Err(err) => warn!("Error reading spells from file: {}", err)
            };
            }
          }
        }
      }
    }
  } else {
    warn!("Data path '{}' does not exist, no data imported", data_dir_path);
  }
}
