from contextlib import contextmanager
import subprocess
import pytest

from . import boardtype


def set_power(on):
    value = 'on' if on else 'auto'
    address = '10' if boardtype.is_birch() else '2d'
    with open('/sys/bus/i2c/devices/2-0020/power/control', 'w') as f:
        f.write(value)
    with open('/sys/bus/i2c/devices/3-00' + address + '/power/control', 'w') as f:
        f.write(value)


@contextmanager
def power_up():
    set_power(True)
    try:
        yield
    finally:
        set_power(False)


@pytest.mark.skipif(
    boardtype.is_birch(),
    reason="Birch is missing the connection to the shutdown line.")
@pytest.mark.skipif(not boardtype.is_librem5(), reason="Not a phone")
def test_selfie_camera_i2c():
    with power_up():
        # TODO: bringup depends on the kernel
        readout = subprocess.check_output([
            'i2ctransfer',
            '-f',  # don't let the loaded driver prevent the test
            '-y', '2',
            'w2@0x20', '0x0f', '0x16', 'r2'])
        assert(readout == b'0x46 0x08\n')


@pytest.mark.skipif(not boardtype.is_librem5(), reason="Not a phone")
def test_big_camera_i2c():
    with power_up():
        address = '0x10' if boardtype.is_birch() else '0x2d'
        readout = subprocess.check_output([
            'i2ctransfer',
            '-f',  # don't let the loaded driver prevent the test
            '-y', '3',
            'w2@' + address, '0x00', '0x00', 'r2'])
        assert(readout == b'0x30 0xc6\n')


@pytest.mark.skipif(not boardtype.is_librem5(), reason="Not a phone")
def test_big_camera_focus_driver():
    """Tests the focus driver based on observed behaviour."""

    def regsetread(byte1, byte2):
        # The driver should be at 0x18 according to the datasheet,
        # so leaving this for easy change.
        address = '0x0c'
        return subprocess.check_output([
            'i2ctransfer',
            '-f',  # don't let any loaded driver prevent the test
            '-y', '3',
            'w2@' + address, byte1, byte2, 'r2'])

    with power_up():
        # Set config bits.
        readout = regsetread('0x00', '0x0f')
        assert(readout == b'0x00 0x0f\n')
        # Switch to "Ringing setting" mode,
        # which probably means "Change settings".
        readout = regsetread('0xec', '0xa3')
        assert(readout == b'0x00 0x00\n')
        # Switch back to drive mode.
        readout = regsetread('0xdc', '0x51')
        assert(readout == b'0x00 0x0f\n')
