use std::fs::File;
use std::io::{BufReader, Read};
use std::path::PathBuf;

use serde_derive::Deserialize;

use crate::config::*;
use crate::id::Id;
use crate::result::RudeResult;
use crate::try_print;

/// Game configuration
#[derive(Clone, Debug, Deserialize)]
pub struct Config {
	/// Directory to hold world and players
	pub database: PathBuf,

	/// Server configuration
	pub server: Server,

	/// Logging configuration
	pub logging: Logging,

	/// Default starting location
	pub starting_location: Id,
}

impl Config {
	/// Load and deserialize the toml configuration from the given file.
	pub fn load<P: Into<PathBuf>>(path: P) -> RudeResult<Self> {
		let path = path.into();

		log::debug!("Reading file {}", path.display());

		let file: File = try_print!(
			File::open(path.clone()),
			"Unable to open file: {}",
			path.display(),
		);

		let mut buffer = BufReader::new(file);
		let mut file_contents = String::new();

		try_print!(
			buffer.read_to_string(&mut file_contents),
			"Unable to read file: {}",
			path.display(),
		);

		Ok(try_print!(
			toml::from_str(&file_contents),
			"Unable to parse toml: {}",
			path.display(),
		))
	}
}