use std::env::current_exe;
use log::{error, info};
use crate::service::detect::detect_service;
use crate::util::check_server_url;

pub fn cli_start(name: &str) {
    info!("Detecting service manager...");
    let service = detect_service();
    if let Some(sm) = service {
        match sm.start(name) {
            Ok(_) => (),
            Err(e) => {
                error!("Error starting service: {}", e);
                std::process::exit(1);
            }
        }
    } else {
        error!("Unable to determine which service manager to use. Could not start.");
        std::process::exit(1);
    }
}

pub fn cli_stop(name: &str) {
    info!("Detecting service manager...");
    let service = detect_service();
    if let Some(sm) = service {
        match sm.stop(name) {
            Ok(_) => (),
            Err(e) => {
                error!("Error starting service: {}", e);
                std::process::exit(1);
            }
        }
    } else {
        error!("Unable to determine which service manager to use. Could not stop.");
        std::process::exit(1);
    }
}

pub fn cli_install(name: &str, server: &str) {
    info!("Checking server url...");
    check_server_url(server);

    info!("Detecting service manager...");
    let service = detect_service();
    if let Some(sm) = service {
        let current_file = match current_exe() {
            Ok(e) => e,
            Err(e) => {
                error!("Unable to get current binary: {}", e);
                std::process::exit(1);
            }
        };
        match sm.install(current_file, name, server) {
            Ok(_) => (),
            Err(e) => {
                error!("Error creating service files: {}", e);
                std::process::exit(1);
            }
        }
    } else {
        error!("Unable to determine which service manager to use. Could not install.");
        std::process::exit(1);
    }
}

pub fn cli_uninstall(name: &str) {
    info!("Detecting service manager...");
    let service = detect_service();
    if let Some(sm) = service {
        match sm.uninstall(name) {
            Ok(_) => (),
            Err(e) => {
                error!("Error removing service files: {}", e);
                std::process::exit(1);
            }
        }
    } else {
        error!("Unable to determine which service manager to use. Could not install.");
        std::process::exit(1);
    }
}