from unittest.mock import Mock

import pytest

from fenrirscreenreader.commands.commands.forward_keypress import command
from fenrirscreenreader.core.fenrirManager import FenrirManager


@pytest.mark.unit
def test_forward_keypress_arms_when_command_keys_are_still_down():
    env = {
        "input": {"key_forward": 0},
        "runtime": {
            "InputManager": Mock(no_key_pressed=Mock(return_value=False)),
            "OutputManager": Mock(present_text=Mock()),
        },
    }
    forward_command = command()
    forward_command.initialize(env)

    forward_command.run()

    assert env["input"]["key_forward"] == -1


@pytest.mark.unit
def test_forward_keypress_activates_immediately_when_keyboard_is_idle():
    env = {
        "input": {"key_forward": 0},
        "runtime": {
            "InputManager": Mock(no_key_pressed=Mock(return_value=True)),
            "OutputManager": Mock(present_text=Mock()),
        },
    }
    forward_command = command()
    forward_command.initialize(env)

    forward_command.run()

    assert env["input"]["key_forward"] == 1


@pytest.mark.unit
def test_forward_keypress_waits_for_command_release_before_forwarding():
    input_manager = Mock(no_key_pressed=Mock(return_value=False))
    manager = FenrirManager.__new__(FenrirManager)
    manager.environment = {
        "input": {"key_forward": -1},
        "runtime": {"InputManager": input_manager},
    }

    manager.update_key_forward()
    assert manager.environment["input"]["key_forward"] == -1

    input_manager.no_key_pressed.return_value = True
    manager.update_key_forward()

    assert manager.environment["input"]["key_forward"] == 1


@pytest.mark.unit
def test_forward_keypress_stays_active_until_forwarded_key_release():
    input_manager = Mock(no_key_pressed=Mock(return_value=False))
    manager = FenrirManager.__new__(FenrirManager)
    manager.environment = {
        "input": {"key_forward": 1},
        "runtime": {"InputManager": input_manager},
    }

    manager.update_key_forward()
    assert manager.environment["input"]["key_forward"] == 1

    input_manager.no_key_pressed.return_value = True
    manager.update_key_forward()

    assert manager.environment["input"]["key_forward"] == 0
