use core::ptr::write_bytes;

use fpga_lib_macros::include_font_plate;

pub const VGA_ADDRESS: *mut Color = 0x80000000 as *mut Color;
pub const WIDTH: usize = 320;
pub const HEIGHT: usize = 240;

#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct Color(pub u8);

impl Color {
    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
        Self(((r >> 6) << 6) | ((g >> 5) << 3) | (b >> 5))
    }
}

pub const WHITE: Color = Color::from_rgb(255, 255, 255);
pub const GRAY: Color = Color::from_rgb(128, 128, 128);
pub const LIGHT_GRAY: Color = Color::from_rgb(128, 64, 64);
pub const BLACK: Color = Color::from_rgb(0, 0, 0);
pub const RED: Color = Color::from_rgb(255, 0, 0);
pub const GREEN: Color = Color::from_rgb(0, 255, 0);
pub const BLUE: Color = Color::from_rgb(0, 0, 255);

pub struct VGA {}

impl VGA {
    /// # Safety
    /// `x` must be less than `WIDTH` and `y` must be less than `HEIGHT`
    pub unsafe fn write_pixel_unsafe(x: u16, y: u16, color: Color) {
        let pixel_index = x as usize + y as usize * WIDTH;
        let word_index = pixel_index / 4; // Get index of the word in which the pixel is
        let byte_index = pixel_index % 4; // Get index of the byte within the word for the pixel

        unsafe { *VGA_ADDRESS.add(word_index * 4 + (3 - byte_index)) = color }
    }

    /// # Safety
    /// `x` must be less than `WIDTH` and `y` must be less than `HEIGHT`
    pub unsafe fn draw_char(x: u16, y: u16, c: char, color: Color) {
        let c = if (c as u8 > b'~') || ((c as u8) < b' ') {
            b'/' - b' '
        } else {
            c as u8 - b' '
        };

        // Get char position within font plate
        let char_x = (c as usize % 32) * FONT_WIDTH;
        let char_y = (c as usize / 32) * FONT_HEIGHT;

        for i in 0..(FONT_WIDTH as u16) {
            for j in 0..(FONT_HEIGHT as u16) {
                let xx = x + i;
                let yy = y + j;

                if xx < (WIDTH as u16)
                    && yy < (HEIGHT as u16)
                    && unsafe { Self::font_plate_index(char_x as u16 + i, char_y as u16 + j) }
                {
                    unsafe { Self::write_pixel_unsafe(xx, yy, color) }
                }
            }
        }
    }

    pub unsafe fn draw_char_bg(x: u16, y: u16, c: char, color: Color, bg_color: Color) {
        let c = if (c as u8 > b'~') || ((c as u8) < b' ') {
            b'/' - b' '
        } else {
            c as u8 - b' '
        };

        // Get char position within font plate
        let char_x = (c as usize % 32) * FONT_WIDTH;
        let char_y = (c as usize / 32) * FONT_HEIGHT;

        for i in 0..(FONT_WIDTH as u16) {
            for j in 0..(FONT_HEIGHT as u16) {
                let xx = x + i;
                let yy = y + j;

                if xx < (WIDTH as u16) && yy < (HEIGHT as u16) {
                    if unsafe { Self::font_plate_index(char_x as u16 + i, char_y as u16 + j) } {
                        unsafe { Self::write_pixel_unsafe(xx, yy, color) }
                    } else {
                        unsafe { Self::write_pixel_unsafe(xx, yy, bg_color) }
                    }
                }
            }
        }
    }

    /// # Safety
    /// The text must have a length that can fit within a `u16`
    pub unsafe fn draw_string(x: u16, y: u16, str: &str, color: Color) {
        str.chars().enumerate().for_each(|(i, c)| unsafe {
            Self::draw_char(x + i as u16 * (FONT_WIDTH as u16), y, c as char, color)
        });
    }
    pub fn clear_screen(color: Color) {
        unsafe { write_bytes(VGA_ADDRESS, color.0, WIDTH * HEIGHT) };
    }

    fn digit_count(mut val: u64) -> u64 {
        let mut i = 0;
        while val != 0 {
            val /= 10;
            i += 1;
        }

        i
    }

    pub unsafe fn draw_u64(x: u16, y: u16, mut val: u64, color: Color, bg_color: Color) {
        if val == 0 {
            unsafe { Self::draw_char_bg(x, y, '0', color, bg_color) }
            return;
        }
        let digit_count = Self::digit_count(val) - 1;
        let mut i = digit_count as u16;
        while val != 0 {
            let digit = val % 10;
            val /= 10;

            let char = (digit as u8) + b'0';
            unsafe {
                Self::draw_char_bg(
                    x + i * (FONT_WIDTH as u16),
                    y,
                    char as char,
                    color,
                    bg_color,
                )
            };

            i -= 1;
        }
    }

    unsafe fn font_plate_index(x: u16, y: u16) -> bool {
        let pixel_index = (y as usize) * FONTPLATE_WIDTH + (x as usize);
        let byte_index = pixel_index / 8;
        let bit_index = pixel_index % 8;

        (FONTPLATE[byte_index] >> bit_index) & 0b1 == 0b1
    }
}

pub const FONT_WIDTH: usize = 6;
pub const FONT_HEIGHT: usize = 13;
pub const FONTPLATE_WIDTH: usize = 32 * FONT_WIDTH;
pub const FONTPLATE_HEIGHT: usize = 3 * FONT_HEIGHT;
pub const FONTPLATE_SIZE: usize = FONTPLATE_WIDTH * FONTPLATE_HEIGHT / 8;
pub const FONTPLATE: [u8; FONTPLATE_SIZE] = include_font_plate! {"fontplate.png"};
