Documentation
use clap::Error;
use flate2::read::GzDecoder;
use tar::Archive;
use toml::Table;
use std::path::PathBuf;
use std::{env::var, fs::{File, remove_dir_all}, path::Path};
use crate::interwebz;
use crate::config;

pub fn open_package(package_name: String, local_pkg: bool) -> Result<Table, std::io::Error> {
    if !local_pkg {
        interwebz::download_from_the_giterwebs(&package_name).expect("cannot download from git! do you have internet, or does the repo not exist?");
        let tar_gz = File::open("/tmp/pkg.ospk")?;
        let tar = GzDecoder::new(tar_gz);
        let mut archive = Archive::new(tar);
        let repo_name = package_name.split('/').last().unwrap_or(&package_name);
        let unpack_path_str = format!("{}/.ospl/{}/", var("HOME").unwrap(), repo_name);
        let unpack_path = Path::new(&unpack_path_str);

        for entry in archive.entries()? {
            let mut entry = entry?;
            let path = entry.path()?.into_owned();
            if let Ok(p) = path.strip_prefix(path.components().next().unwrap()) {
                if !p.as_os_str().is_empty() {
                    let final_path = unpack_path.join(p);
                    if let Some(parent) = final_path.parent() {
                        std::fs::create_dir_all(parent)?;
                    }
                    entry.unpack(&final_path)?;
                }
            }
        }

        let ospm_toml_path = unpack_path.join("ospm.toml");
        let main_ospl_path = unpack_path.join("main.ospl");

        if !main_ospl_path.exists() {
            println!("DANGER: the package you just installed DOES NOT have a main.ospl file. this may result in unexpected behaviour!")
        }
        return Ok(config::prase(&ospm_toml_path));
    } else {
        let path = format!("{}.ospk", package_name);
        println!("locally installing: if this was not intended, do not add the -l flag");
        let tar_gz = File::open(path)?;
        let tar = GzDecoder::new(tar_gz);
        let mut archive = Archive::new(tar);
        archive.unpack(var("HOME").unwrap() + "/.ospl/" + &package_name + "/")?;
    }
    if !Path::new(&(var("HOME").unwrap() + "/.ospl/" + &package_name + "/main.ospl")).exists() {
        println!("DANGER: the package you just installed DOES NOT have a main.ospl file. this may result in unexpected behaviour!")
    }
    Ok(query_package(package_name))
}

pub fn remove_package(package_name: String) {
    println!("removing package...");
    let mut buf = PathBuf::new();
    buf.push(var("HOME").expect("where's your home directory?"));
    buf.push(".ospl");
    buf.push(package_name);
    remove_dir_all(buf).expect("fuck you magic man");  // may or may not work idk
    println!("done!");
}

pub fn query_package(package_name: String) -> Table{
    config::prase(Path::new(&(var("HOME").unwrap() + "/.ospl/" + &package_name + "/ospm.toml")))
}