use crate::v4::{LeaseConfig, MessageOptions, SocketConfig};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{OpenOptions, read_to_string};
use std::io::Write;
use std::net::Ipv4Addr;
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
use toml;
use tracing::{info, warn};

/// Configuration used specifically within a `Server`.
/// This differs from `ServerConfig` which bundles many configs, including:
/// 'InnerServerConfig`, `SocketConfig`, and `LeasesConfig`.
#[derive(Serialize, Deserialize, Debug)]
pub struct InnerServerConfig {
    /// Controls whether the server agrees to use [Rapid Commit](crate::v4::MessageOptions::RapidCommit).
    pub rapid_commit: bool,
    /// May or may not match the IP address in `SocketConfig.listen_address`.
    /// For example, you might be listening to `0.0.0.0`, but your server has another address it can be reached from.
    /// This is used in both the `siaddr` field and `ServerIdentifier` option.
    ///
    /// If `None`, then `listen_address` is used.
    pub server_address: Option<Ipv4Addr>,
    /// DHCP option numbers (as a String) mapped to values that are used to respond to parameter request list options
    pub parameters: HashMap<u8, MessageOptions>,
}

impl Default for InnerServerConfig {
    fn default() -> Self {
        Self {
            rapid_commit: true,
            server_address: None,
            parameters: HashMap::with_capacity(u8::MAX as usize),
        }
    }
}

/// Representation of a `toe-beans.toml` file. Used by the [Server](crate::v4::Server).
///
/// This is exported for you to use in your application to generate a `toe-beans.toml`.
#[derive(Serialize, Deserialize, Debug)]
pub struct ServerConfig {
    /// The path to a directory where this config will exist on disk.
    #[serde(skip)]
    pub path: PathBuf,
    /// A subtable of configuration that is specific to, and used by, the `Server`.
    pub server: InnerServerConfig,
    /// A subtable of configuration that is specific to, and passed to, a `Socket` by both a `Server` and a `Client`.
    pub socket_config: SocketConfig,
    /// A subtable of configuration that is specific to, and passed to, a `Leases` by the `Server`.
    pub lease_config: LeaseConfig,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            path: PathBuf::new(), // empty, the current directory
            server: InnerServerConfig::default(),
            socket_config: SocketConfig::default_server(),
            lease_config: LeaseConfig::default(),
        }
    }
}

impl ServerConfig {
    /// The file name that the Config is read from and written to.
    pub const FILE_NAME: &'static str = "toe-beans.toml";

    /// Reads the `toe-beans.toml` file and deserializes it into a Config.
    /// Returns default options if there are any issues.
    pub fn read(from_where: PathBuf) -> Self {
        let read_result = read_to_string(from_where.join(Self::FILE_NAME));
        if let Ok(config_string) = read_result {
            let toml_result = toml::from_str(&config_string);
            match toml_result {
                Ok(config) => {
                    return Self {
                        path: from_where, // from_where might be different if passed through cli args
                        ..config
                    };
                }
                Err(error) => {
                    warn!("{error}");
                    warn!(
                        "Warning: invalid {}. Using default values.",
                        Self::FILE_NAME
                    );
                }
            }
        } else {
            warn!(
                "Warning: can't read {}. Using default values.",
                Self::FILE_NAME
            );
        }

        Self {
            path: from_where,
            ..ServerConfig::default()
        }
    }

    /// Serializes a Config and writes it to a `toe-beans.toml` file.
    pub fn write(&self) {
        info!("Writing {}", Self::FILE_NAME);

        let config_content = toml::to_string_pretty(self).expect("Failed to generate toml data");
        let mode = 0o600;

        let mut file = OpenOptions::new()
            .read(false)
            .write(true)
            .create(true)
            .truncate(true)
            .mode(mode) // ensure that file permissions are set before creating file
            .open(self.path.join(Self::FILE_NAME))
            .unwrap_or_else(|_| panic!("Failed to open config {} for writing", Self::FILE_NAME));

        file.write_all(config_content.as_bytes())
            .unwrap_or_else(|_| panic!("Failed to write config to {}", Self::FILE_NAME));
    }
}
