"""Tests for key normalization."""

from pyos import Keys
from pyos.Activity import Activity
from pyos.EventTypes import KeyStroke


class TestNormalize:
    def test_cr_to_enter(self):
        assert Keys.normalize(13) == Keys.ENTER

    def test_curses_key_enter_to_enter(self):
        assert Keys.normalize(343) == Keys.ENTER  # raw KEY_ENTER value

    def test_del_to_backspace(self):
        assert Keys.normalize(127) == Keys.BACKSPACE

    def test_curses_key_backspace_to_backspace(self):
        assert Keys.normalize(263) == Keys.BACKSPACE  # raw KEY_BACKSPACE value

    def test_passthrough_regular_key(self):
        assert Keys.normalize(ord("a")) == ord("a")

    def test_passthrough_esc(self):
        assert Keys.normalize(Keys.ESC) == Keys.ESC

    def test_passthrough_tab(self):
        assert Keys.normalize(Keys.TAB) == Keys.TAB

    def test_enter_stays_enter(self):
        assert Keys.normalize(Keys.ENTER) == Keys.ENTER

    def test_backspace_stays_backspace(self):
        assert Keys.normalize(Keys.BACKSPACE) == Keys.BACKSPACE


class TestHarnessNormalization:
    """Integration: send_key normalizes before dispatching."""

    def test_send_127_arrives_as_backspace(self, app, mock_screen):
        received = []

        class Spy(Activity):
            def on_start(self):
                self.application.subscribe(KeyStroke, self, lambda e: received.append(e.key))

        app.start_activity(Spy())
        app.send_key(127)

        assert received == [Keys.BACKSPACE]

    def test_send_13_arrives_as_enter(self, app, mock_screen):
        received = []

        class Spy(Activity):
            def on_start(self):
                self.application.subscribe(KeyStroke, self, lambda e: received.append(e.key))

        app.start_activity(Spy())
        app.send_key(13)

        assert received == [Keys.ENTER]

    def test_send_curses_key_enter_arrives_as_enter(self, app, mock_screen):
        received = []

        class Spy(Activity):
            def on_start(self):
                self.application.subscribe(KeyStroke, self, lambda e: received.append(e.key))

        app.start_activity(Spy())
        app.send_key(343)  # raw KEY_ENTER value

        assert received == [Keys.ENTER]
