import pytest

from sangaboard import Sangaboard
from sangaboard.extensible_serial_instrument import DummySerialDevice

class DummySangaboardPort(DummySerialDevice):
    """Create a dummy port, with the minimal responses to work

    When the Sangaboard class is initialised, it checks the board,
    the version, and the optional modules.  All of those commands
    must therefore return reasonable values.
    """
    blocking_moves = False

    def __init__(self, firmware_version="Sangaboard Firmware v0.5.1"):
        self.register_response("version", f"{firmware_version}\r\n")
        self.register_response("list_modules", "--END--\r\n")
        self.register_response("board", "Sangaboard v0.3\r\n")
        self.register_response("blocking_moves (false|true)", self.set_blocking_moves)
        self.print_buffers = True

    def set_blocking_moves(self, groups):
        self.blocking_moves = "true" in groups[0]
        return "done\r\n"


def test_version_0_5():
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v0.5\r\n")
    sb = Sangaboard(port)
    assert sb.firmware_version == '0.5'
    assert sb.version_tuple == (0, 5)

def test_version_0_5_1():
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v0.5.1\r\n")
    sb = Sangaboard(port)
    assert sb.firmware_version == '0.5.1'
    assert sb.version_tuple == (0, 5)

def test_version_1_0_1():
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v1.0.1\r\n")
    sb = Sangaboard(port)
    assert sb.firmware_version == '1.0.1'
    assert sb.version_tuple == (1, 0)

def test_version_1_0_0_alpha(caplog):
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v1.0.0-alpha1\r\n")
    sb = Sangaboard(port)
    assert sb.firmware_version == '1.0.0-alpha1'
    assert sb.version_tuple == (1, 0)
    assert "prerelease firmware" in caplog.text

def test_version_1_0_1_enables_blocking_moves():
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v1.0.1\r\n")
    sb = Sangaboard(port)
    assert port.blocking_moves

def test_version_0_5_blocking_moves():
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v0.5\r\n")
    sb = Sangaboard(port)
    assert not port.blocking_moves

def test_version_0_5_1_custom():
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v0.5.1-custom\r\n")
    sb = Sangaboard(port)
    assert sb.firmware_version == '0.5.1-custom'
    assert sb.version_tuple == (0, 5)

def test_version_0_6_0():
    port = DummySangaboardPort(firmware_version="Sangaboard Firmware v0.6.0\r\n")
    with pytest.raises(IOError):
        Sangaboard(port)

def test_version_0_3():
    port = DummySangaboardPort(firmware_version="OpenFlexure Motor Driver Firmware v0.3\r\n")
    with pytest.raises(IOError):
        Sangaboard(port)
