use crate::colors::get_colors;
use crate::config::get_config;
use crate::download::download;
use crate::options::Options;
use crate::utils::{confirm, package_exists, prepare_packages};
use std::slice::from_ref;

/// Downloads sources and copies `SlackBuild` scripts into the configured fetch directory
/// without building or installing.
///
/// # Exits
///
/// Exits with a non-zero code if a package is not found in the repository.
pub fn fetch(packages: &[String], options: &Options) {
    let packages = package_exists(packages);
    let packages = prepare_packages(&packages);

    let cfg = get_config();
    let color = get_colors(cfg.colors);

    println!(
        "{}Fetch package(s) with sources into {}{}",
        color.bold, cfg.fetch_path, color.reset
    );

    println!("Package(s) ({}) to fetch:", packages.len());
    for package in &packages {
        println!("  {}{}{}", color.cyan, package, color.reset);
    }

    confirm("\nContinue? [Y/n]: ", options.no_confirm);

    for package in &packages {
        download(from_ref(package), options, &cfg.fetch_path);
    }

    println!("Fetched ({}) package(s):", packages.len());
    for fetch in packages {
        println!("  {}{}", cfg.fetch_path, fetch);
    }

    println!(
        "\n{}{}Fetch complete.{}",
        color.bold, color.green, color.reset
    );
}
