use std::error::Error;
use std::path::PathBuf;
use log::debug;
use crate::service::codegen::ServiceFileGenerator;
use std::fmt::Write;
use std::fs;

pub struct SystemDServiceFileGenerator {}
impl ServiceFileGenerator for SystemDServiceFileGenerator {
    fn create_service_files(bin_path: PathBuf, name: &str, server: &str) -> Result<(), Box<dyn Error>> {
        debug!("Generating a unit file...");

        let mut unit_file = String::new();
        writeln!(unit_file, "[Unit]")?;
        writeln!(unit_file, "Description=A client for Defined Networking compatible overlay networks (instance {})", name)?;
        writeln!(unit_file, "Wants=basic.target network-online.target")?;
        writeln!(unit_file, "After=basic.target network.target network-online.target")?;
        writeln!(unit_file)?;
        writeln!(unit_file, "[Service]")?;
        writeln!(unit_file, "SyslogIdentifier=tfclient-{}", name)?;
        writeln!(unit_file, "ExecStart={} run --server {} --name {}", bin_path.as_path().display(), server, name)?;
        writeln!(unit_file, "Restart=always")?;
        writeln!(unit_file)?;
        writeln!(unit_file, "[Install]")?;
        writeln!(unit_file, "WantedBy=multi-user.target")?;

        fs::write(format!("/usr/lib/systemd/system/{}.service", SystemDServiceFileGenerator::get_service_file_name(name)), unit_file)?;

        debug!("Installed unit file");

        Ok(())
    }

    fn delete_service_files(name: &str) -> Result<(), Box<dyn Error>> {
        debug!("Deleting unit file...");

        fs::remove_file(format!("/usr/lib/systemd/system/{}.service", SystemDServiceFileGenerator::get_service_file_name(name)))?;

        debug!("Removed unit file");

        Ok(())
    }
}
impl SystemDServiceFileGenerator {
    pub fn get_service_file_name(name: &str) -> String {
        format!("tfclient_i-{}", name)
    }
}