use crate::rom::palette_cycle::PaletteCycle;
use crate::rom::rom_graphics::RomGraphics;
use crate::rom::{self};

#[derive(Debug)]
pub struct BackgroundGraphics {
    array_rom_graphics: Vec<i16>,
    rom_graphics: RomGraphics,
}

impl BackgroundGraphics {
    pub fn new(index: usize, bits_per_pixel: u8) -> Self {
        let mut background_graphics = BackgroundGraphics {
            array_rom_graphics: vec![],
            rom_graphics: RomGraphics::new(bits_per_pixel),
        };

        background_graphics.read(index);

        background_graphics
    }

    fn read(&mut self, index: usize) {
        // Graphics pointer table entry
        let mut graphics_pointer_block = rom::read_block(0xD7A1 + index * 4);
        // Read graphics
        self.rom_graphics
            .load_graphics(rom::read_block(rom::snes_to_hex(
                graphics_pointer_block.read_int32() as usize,
                true,
            )));
        // Arrangement pointer table entry
        let mut array_pointer_block = rom::read_block(0xD93D + index * 4);
        let array_pointer = rom::snes_to_hex(array_pointer_block.read_int32() as usize, true);
        // Read and decompress arrangement
        let mut array_block = rom::read_block(array_pointer);
        self.array_rom_graphics = array_block.decompress();
    }

    pub fn draw(&mut self, bitmap: &mut [i16], palette: &PaletteCycle) {
        self.rom_graphics
            .draw(bitmap, palette, &self.array_rom_graphics);
    }
}
