use gba::fatal;
use gba::prelude::*;

use crate::gfx;
use core::fmt::Write;
use gba_utils::gfx::{Default8x8, Subpixel4x8};

static mut IS_PANICKING: bool = false;

/// Handles panics by putting up a screen showing an exclamation mark,
/// and writing a message to mGBA (if available), then looping.
#[panic_handler]
#[allow(unreachable_code)]
fn panic(info: &core::panic::PanicInfo) -> ! {
    unsafe { IME.write(false) };

    /* In case any routines we use here panic. */
    unsafe {
        if IS_PANICKING {
            fatal!("Panicked twice?! Info: {}", info);
            loop {}
        }
        IS_PANICKING = true;
    }

    let di = gfx::text_mode_setup(true);
    let mut writer = gfx::GfxWriter::<Subpixel4x8>::new(0, 0, di);

    // fatal!("{}", info);

    write!(writer, "PANIC").ok();
    writer.newline();
    writer.newline();
    write!(writer, "{}", info).ok();

    /*
    const FGCOLOR: Color = Color::from_rgb(28, 15, 20);
    const BGCOLOR: Color = Color::from_rgb(15, 5, 8);
    Mode3::dma_clear_to(BGCOLOR);

    for i in 0..10
    {
        Mode3::write(Mode3::WIDTH / 2, Mode3::HEIGHT / 2 - i, FGCOLOR);
        Mode3::write(Mode3::WIDTH / 2 - 1, Mode3::HEIGHT / 2 - i, FGCOLOR);
        Mode3::write(Mode3::WIDTH / 2 + 1, Mode3::HEIGHT / 2 - i, FGCOLOR);
    }

    Mode3::write(Mode3::WIDTH / 2, Mode3::HEIGHT / 2 + 3, FGCOLOR);
    Mode3::write(Mode3::WIDTH / 2 + 1, Mode3::HEIGHT / 2 + 3, FGCOLOR);
    Mode3::write(Mode3::WIDTH / 2 - 1, Mode3::HEIGHT / 2 + 3, FGCOLOR);
    */

    loop {}
}
