use crate::colors::get_colors;
use crate::config::get_config;
use crate::load_data::load_data_json;
use crate::utils::{package_exists, prepare_packages};

/// Prints all packages in the repository that depend on each requested package.
pub fn reverse(packages: &[String]) {
    let packages = package_exists(packages);
    let packages = prepare_packages(&packages);

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

    let repo = load_data_json();

    println!(
        "{}Reverse dependencies for package(s):{}\n",
        color.bold, color.reset
    );

    for pkg in &packages {
        if let Some(pkg_data) = repo.get(pkg) {
            println!("{}{}-{}:{}", color.cyan, pkg, pkg_data.version, color.reset);
        }

        let mut found = false;
        for (k, v) in &repo {
            if v.requires.split_whitespace().any(|r| r == pkg) {
                found = true;
                println!("  {} {}({}){}", k, color.yellow, v.version, color.reset);
            }
        }

        if !found {
            println!("  No reverse dependencies found");
        }

        println!();
    }
}
