from . import boardtype

import os
import pytest
import subprocess


@pytest.fixture
def tempdir():
    import tempfile
    with tempfile.TemporaryDirectory() as tmpdir:
        yield tmpdir


@pytest.mark.skipif(not boardtype.is_devkit(), reason="Not a devkit")
def test_sgtl5000():
    "Check if the sgtl5000 audio codec is there"
    out = subprocess.check_output(["aplay", "-l"])
    assert b"[sgtl5000]" in out


@pytest.mark.skipif(not boardtype.is_librem5(), reason="Not a phone")
def test_wm8962():
    "Check if the audio codec is there"
    out = subprocess.check_output(["aplay", "-l"])
    assert b"[wm8962]" in out


def test_headphone_detection():
    "Check if we registered the headphone detection IRQ"
    f = open("/proc/interrupts")
    assert " HP_DET" in f.read()


def test_sound_output(tempdir):
    if boardtype.is_librem5():
        output = 'wm8962'
    else:
        output = 'sgtl5000'
    out = subprocess.run(["alsabat",
                          "-D",
                          "plughw:CARD={},DEV=0".format(output),
                          "-f",
                          "dat",
                          "--saveplay",
                          os.path.join(tempdir, 'default_dual.wav'),
                          "--standalone"],
                         capture_output=True)
    assert(b"Return value is 0" in out.stdout)
    assert(out.returncode == 0)
