import unittest

from h8536.emulator import MemoryMap
from h8536.emulator.peripherals import LCD_E_CLOCK_DATA, LCD_E_CLOCK_STATUS


class EmulatorLcdBusTest(unittest.TestCase):
    def test_status_read_reports_ready_even_after_command_write(self):
        memory = MemoryMap(b"\x00" * 4)
        memory.write8(LCD_E_CLOCK_STATUS, 0x80)

        self.assertEqual(memory.read8(LCD_E_CLOCK_STATUS), 0x00)

    def test_data_read_returns_data_latch_defaulting_to_zero(self):
        memory = MemoryMap(b"\x00" * 4)

        self.assertEqual(memory.read8(LCD_E_CLOCK_DATA), 0x00)

        memory.write8(LCD_E_CLOCK_DATA, 0x41)

        self.assertEqual(memory.read8(LCD_E_CLOCK_DATA), 0x41)

    def test_command_sets_ddram_cursor_and_data_updates_display_text(self):
        memory = MemoryMap(b"\x00" * 4)

        memory.write8(LCD_E_CLOCK_STATUS, 0x80)
        for value in b"CONNECT: NOT ACT":
            memory.write8(LCD_E_CLOCK_DATA, value)

        self.assertEqual(memory.lcd.line_text(0), "CONNECT: NOT ACT")

    def test_rom_line_mapping_matches_16x4_lcd_addresses(self):
        memory = MemoryMap(b"\x00" * 4)

        memory.write8(LCD_E_CLOCK_STATUS, 0xC0)
        memory.write8(LCD_E_CLOCK_DATA, ord("1"))
        memory.write8(LCD_E_CLOCK_STATUS, 0x90)
        memory.write8(LCD_E_CLOCK_DATA, ord("2"))
        memory.write8(LCD_E_CLOCK_STATUS, 0xD0)
        memory.write8(LCD_E_CLOCK_DATA, ord("3"))

        self.assertTrue(memory.lcd.line_text(1).startswith("1"))
        self.assertTrue(memory.lcd.line_text(2).startswith("2"))
        self.assertTrue(memory.lcd.line_text(3).startswith("3"))


if __name__ == "__main__":
    unittest.main()
