#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use eframe::{
    egui::{widgets, CentralPanel, Context},
    App,
};
use poll_promise::Promise;

use crate::custom_window_frame;

pub struct Launcher {
    latest_version: String,
    update_available: bool,
    download_promise: Option<Promise<Result<String, String>>>,
    server_url: String,
    server_root_uri: String,
    dirtreecontent: Option<String>,
}

// {
// 	"version": "0.1.0",
// 	"files": [
// 		{
// 			"path": "/MyFile",
// 			"hash": "bighashofdoom"
// 		}
// 	]
// }

impl Launcher {
    pub fn new(_cc: &eframe::CreationContext<'_>) -> Self {
        Launcher {
            latest_version: "0.1.0".to_string(),
            update_available: true,
            download_promise: None,
            server_url: "https://ginger.amasson.eu:6886".into(),
            server_root_uri: format!("/Howling/{}", std::env::consts::OS),
            dirtreecontent: None,
        }
    }

    pub fn dirtree_path(&self) -> String {
        format!("{}{}/dirtree.json", self.server_url, self.server_root_uri)
    }
}

impl App for Launcher {
    fn clear_color(&self, _visuals: &eframe::egui::Visuals) -> [f32; 4] {
        eframe::egui::Rgba::TRANSPARENT.to_array()
    }

    fn update(&mut self, ctx: &Context, frame: &mut eframe::Frame) {
        let dirtreepath = self.dirtree_path();

        custom_window_frame::custom_window_frame(ctx, frame, "egui with custom frame", |ui| {
            let promise = self.download_promise.get_or_insert_with(|| {
                let ctx = ctx.clone();
                let (sender, promise) = Promise::new();
                let request = ehttp::Request::get(&dirtreepath);

                println!("Downloading from {}", &dirtreepath);
                ehttp::fetch(request, move |response| {
                    let dirtreefile = response.and_then(|res| {
                        let bytes = res.bytes;
                        Ok(String::from_utf8(bytes).unwrap())
                    });
                    sender.send(dirtreefile);
                    ctx.request_repaint();
                });
                promise
            });

            ui.heading("Howling Launcher");

            if self.update_available {
                if ui.button("Download Update").clicked() {
                    println!("download update clicked !");

                    CentralPanel::default().show(ctx, |ui| match promise.ready() {
                        None => {
                            ui.spinner();
                            println!("Downloading...");
                        }
                        Some(Err(err)) => {
                            println!("Error downloading {}", err);
                            ui.colored_label(ui.visuals().error_fg_color, err);
                        }
                        Some(Ok(text)) => {
                            println!("Finished downloading");
                            self.dirtreecontent = Some(text.clone());
                        }
                    });

                    self.update_available = false;
                }
            } else {
                if let Some(text) = self.dirtreecontent.clone() {
                    ui.label(format!("dirtree:\n{}\n", text));
                }

                ui.label(format!(
                    "version: {} - You're up to date !",
                    self.latest_version
                ));
            }

            if ui.button("Play").clicked() {
                println!("play clicked !");
            }

            ui.add_space(ui.available_size_before_wrap().y / 2.0);

            ui.horizontal(|ui| {
                ui.label("egui theme:");
                widgets::global_dark_light_mode_buttons(ui);
            });
        });
    }
}
