use flate2::read::GzDecoder;
use std::{
    env,
    fs::File,
    io::{BufRead, Cursor, Seek, Write},
    path::PathBuf,
    process::Command,
    str::FromStr,
};
use tar::Archive;
//use tauri::file;

use crate::{
    https, java,
    system_dirs::{get_local_data_directory, get_prism_executable},
    util,
};

pub fn check_prism() -> bool {
    let path = get_local_data_directory().join("prism");
    path.exists()
}

#[tauri::command]
pub async fn install_prism(window: tauri::AppHandle) {
    if check_prism() {
        return;
    }
    java::install_java(21, window.clone()).await;
    let mut buff = Cursor::new(vec![]);
    let mut total = 0;
    //ftp::ftp_retr(Some(window.clone()), path, &mut buff, |window: Option<tauri::Window>, data, size| util::download_callback("Prism Launcher".to_string(),window, data, size)).unwrap();
    https::download(
        Some(window.clone()),
        format!(
            "https://gitea.piwalker.net/fclauncher/prism/prism-{}",
            if env::consts::OS == "windows" {
                "win.zip"
            } else {
                "lin.tar.gz"
            }
        ),
        &mut buff,
        format!("Prism Launcher"),
    )
    .await;
    std::fs::create_dir_all(get_local_data_directory().join("prism")).unwrap();
    buff.rewind().unwrap();
    if env::consts::OS != "windows" {
        let tar = GzDecoder::new(buff);
        let mut archive = Archive::new(tar);
        if !archive
            .unpack(get_local_data_directory().join("prism"))
            .is_ok()
        {
            std::fs::remove_dir_all(get_local_data_directory().join("prism"));
        }
    } else {
        if !zip_extract::extract(
            buff,
            get_local_data_directory().join("prism").as_path(),
            true,
        )
        .is_ok()
        {
            std::fs::remove_dir_all(get_local_data_directory().join("prism"));
        }
    }

    let mut buff = Cursor::new(vec![]);
    //ftp::ftp_retr(Some(window.clone()), PathBuf::new().join("prism").join("prismlauncher.cfg"), &mut buff, |_, _, _| return).unwrap();
    https::download(
        None,
        format!("https://gitea.piwalker.net/fclauncher/prism/prismlauncher.cfg"),
        &mut buff,
        format!("prismlauncher.cfg"),
    )
    .await;
    buff.rewind();
    let mut file = File::create(
        get_local_data_directory()
            .join("prism")
            .join("prismlauncher.cfg"),
    )
    .unwrap();
    loop {
        let mut buf = String::new();
        let count = buff.read_line(&mut buf).unwrap();
        if count == 0 {
            break;
        }
        if buf.starts_with("JavaPath") {
            buf = format!(
                "JavaPath={}/java/java-21-{}\n",
                get_local_data_directory()
                    .to_str()
                    .unwrap()
                    .replace("\\", "/"),
                if env::consts::OS == "windows" {
                    "win"
                } else {
                    "lin"
                }
            );
        } else if buf.starts_with("LastHostname") {
            buf = format!(
                "LastHostname={}\n",
                gethostname::gethostname().to_str().unwrap()
            );
        }
        file.write_all(buf.as_bytes());
    }
}

#[tauri::command]
pub fn launch_prism() {
    let mut child = Command::new(
        get_local_data_directory()
            .join("prism")
            .join(get_prism_executable()),
    )
    .spawn()
    .unwrap();
}
