use emgauwa_lib::{constants, utils};
use serde_derive::Deserialize;

use crate::driver::Driver;

#[derive(Clone, Debug, Deserialize)]
#[serde(default)]
#[allow(unused)]
pub struct Core {
	pub host: String,
	pub port: u16,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(default)]
#[allow(unused)]
pub struct Logging {
	pub level: String,
	pub file: String,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(default)]
#[allow(unused)]
pub struct Relay {
	pub driver: Driver,
	pub name: String,
	pub number: Option<i64>,
	pub pin: u8,
	pub inverted: bool,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(default)]
#[allow(unused)]
pub struct Settings {
	pub core: Core,
	pub database: String,
	pub logging: Logging,
	pub name: String,
	pub relays: Vec<Relay>,
}

impl Default for Settings {
	fn default() -> Self {
		Settings {
			core: Core::default(),
			database: String::from("sqlite://emgauwa-controller.sqlite"),
			logging: Logging::default(),
			name: String::from("Emgauwa Controller"),
			relays: Vec::new(),
		}
	}
}

impl Default for Relay {
	fn default() -> Self {
		Relay {
			driver: Driver::Gpio,
			number: None,
			name: String::from("Relay"),
			pin: 0,
			inverted: false,
		}
	}
}

impl Default for Core {
	fn default() -> Self {
		Core {
			host: String::from("127.0.0.1"),
			port: constants::DEFAULT_PORT,
		}
	}
}

impl Default for Logging {
	fn default() -> Self {
		Logging {
			level: String::from("info"),
			file: String::from("stdout"),
		}
	}
}

pub fn init() -> Settings {
	let mut settings: Settings = utils::load_settings("controller", "CONTROLLER");

	for (num, relay) in settings.relays.iter_mut().enumerate() {
		if relay.number.is_none() {
			relay.number = Some(num as i64);
		}
	}

	settings
}