import re
import pytest

from rfal import synth_signal_names, cavity_factory


@pytest.mark.parametrize(
    ('cm', 'nelem', 'regex'),
    [('01', 8, r'\bACCL:L0B:01[1-8]0:AL:SELECT\b'),
     ('02', 4*8, r'\bACCL:L1B:0[2-3][1-8]0:AL:SELECT\b | '
              r'\bACCL:L1B:H[1-2][1-8]0:AL:SELECT\b'),
     ('H1', 2*8, r'\bACCL:L1B:H[1-2][1-8]1:AL:SELECT\b'),
     ('04', 12*8, r'\bACCL:L2B:0[4-9][1-8]0:AL:SELECT\b | '
               r'\bACCL:L2B:1[0-5][1-8]0:AL:SELECT\b'),
     ('16', 20*8, r'\bACCL:L3B:1[6-9][1-8]0:AL:SELECT\b | '
               r'\bACCL:L3B:2[0-9][1-8]0:AL:SELECT\b | '
               r'\bACCL:L3B:3[0-5][1-8]0:AL:SELECT\b')],
    ids=['L0B', 'L1B', 'HL', 'L2B', 'L3B']
    )
def test_synth_rfal_signals(cm, nelem, regex):
    with pytest.raises(AssertionError):
        synth_signal_names(cm, 'blah', subsys='foo')

    S = synth_signal_names(cm, 'SELECT', subsys='rfal')
    P = re.compile(regex, flags=re.X)

    assert len(S) == nelem
    
    # Check that there are no duplicates
    for s in S:
        assert sum([s_ == s for s_ in S]) == 1

    for s in S:
        assert re.match(P, s) is not None


@pytest.mark.parametrize(
    ('cm', 'nelem', 'regex'),
    [('01', 8, r'\bACCL:L0B:01[1-8]0:AACTMEAN\b'),
     ('02', 4*8, r'\bACCL:L1B:0[2-3][1-8]0:AACTMEAN\b | '
              r'\bACCL:L1B:H[1-2][1-8]0:AACTMEAN\b'),
     ('H1', 2*8, r'\bACCL:L1B:H[1-2][1-8]0:AACTMEAN\b'),
     ('04', 12*8, r'\bACCL:L2B:0[4-9][1-8]0:AACTMEAN\b | '
               r'\bACCL:L2B:1[0-5][1-8]0:AACTMEAN\b'),
     ('16', 20*8, r'\bACCL:L3B:1[6-9][1-8]0:AACTMEAN\b | '
               r'\bACCL:L3B:2[0-9][1-8]0:AACTMEAN\b | '
               r'\bACCL:L3B:3[0-5][1-8]0:AACTMEAN\b')],
    ids=['L0B', 'L1B', 'HL', 'L2B', 'L3B']
    )
def test_synth_llrf_signals(cm, nelem, regex):
    S = synth_signal_names(cm, 'AACTMEAN', subsys='llrf')
    P = re.compile(regex, flags=re.X)

    assert len(S) == nelem

    # Check that there are no duplicates
    for s in S:
        assert sum([s_ == s for s_ in S]) == 1

    for s in S:
        assert re.match(P, s) is not None


def test_cavity_factory_args():
    with pytest.raises(ValueError):
        cavity_factory(None)

    with pytest.raises(ValueError):
        cavity_factory('foo')


@pytest.mark.parametrize(
    ('cm', 'nelem'),
    [('01', 8),
     ('02', 4*8),
     ('H1', 2*8),
     ('04', 12*8),
     ('16', 20*8)],
    ids=['L0B', 'L1B', 'HL', 'L2B', 'L3B']
    )
def test_cavity_factory(cm, nelem):
    cavs = cavity_factory(cm=cm)

    assert len(cavs) == nelem

