use std::{
    env,
    process::ExitCode,
    sync::atomic::{AtomicBool, Ordering},
};

use libcolors::{
    application::{
        window::{EventOutcome, Window},
        Application,
    },
    error::Error, message::{CreateWindowInfo, WindowType},
};
use raqote::{DrawTarget, SolidSource};

fn run_window() -> Result<ExitCode, Error> {
    static FOCUSED: AtomicBool = AtomicBool::new(false);

    println!("libcolors test application");
    let mut app = Application::new()?;
    let mut window = Window::new(&app)?;

    window.set_on_redraw_requested(|surface: &mut DrawTarget<&mut [u32]>| {
        let color = if FOCUSED.load(Ordering::Acquire) {
            SolidSource::from_unpremultiplied_argb(255, 255, 0, 0)
        } else {
            SolidSource::from_unpremultiplied_argb(255, 0, 0, 255)
        };
        let border = 8;
        let border_color = SolidSource::from_unpremultiplied_argb(255, 0, 255, 0);

        let w = surface.width();
        let h = surface.height();
        surface.clear(border_color);
        surface.fill_rect(
            border as _,
            border as _,
            (w - border * 2) as _,
            (h - border * 2) as _,
            &color.into(),
            &Default::default(),
        );
    });
    window.set_on_focus_changed(|focused| {
        FOCUSED.store(focused, Ordering::Release);
        EventOutcome::Redraw
    });

    app.add_window(window);
    Ok(app.run())
}

fn main() -> ExitCode {
    match run_window() {
        Ok(code) => code,
        Err(error) => {
            eprintln!("{error}");
            ExitCode::FAILURE
        }
    }
}
