
PATH_IF_TX_PKTS = PATH_IF + 'state/tx_packets_per_second'
PATH_IF_RX_PKTS = PATH_IF + 'state/rx_packets_per_second'

DEVICE_STATE_IF1_TX_PKTS = PATH_IF_TX_PKTS.format('IF1')
DEVICE_STATE_IF1_RX_PKTS = PATH_IF_RX_PKTS.format('IF1')
DEVICE_STATE_IF2_TX_PKTS = PATH_IF_TX_PKTS.format('IF2')
DEVICE_STATE_IF2_RX_PKTS = PATH_IF_RX_PKTS.format('IF2')


def test_device_driverapi_emulated_subscriptions(
    device_driverapi_emulated : EmulatedDriver): # pylint: disable=redefined-outer-name

    duration = 10.0
    interval = 1.5
    results = device_driverapi_emulated.SubscribeState([
        (DEVICE_STATE_IF1_TX_PKTS, duration, interval),
        (DEVICE_STATE_IF1_RX_PKTS, duration, interval),
        (DEVICE_STATE_IF2_TX_PKTS, duration, interval),
        (DEVICE_STATE_IF2_RX_PKTS, duration, interval),
    ])
    LOGGER.info('results:\n{:s}'.format(', '.join(map(str, results))))
    assert len(results) == 4
    for result in results: assert isinstance(result, bool) and result

    stored_config = device_driverapi_emulated.GetConfig()
    LOGGER.info('stored_config:\n{:s}'.format('\n'.join(map(str, stored_config))))

    time.sleep(duration + 1.0) # let time to generate samples, plus 1 second extra time

    samples = []
    for sample in device_driverapi_emulated.GetState(blocking=False):
        LOGGER.info('sample: {:s}'.format(str(sample)))
        timestamp,resource_key,resource_value = sample
        samples.append((timestamp, resource_key, resource_value))
    LOGGER.info('samples:\n{:s}'.format('\n'.join(map(str, samples))))
    assert len(samples) == 4 * (math.floor(duration/interval) + 1)

    results = device_driverapi_emulated.UnsubscribeState([
        (DEVICE_STATE_IF1_TX_PKTS, duration, interval),
        (DEVICE_STATE_IF1_RX_PKTS, duration, interval),
        (DEVICE_STATE_IF2_TX_PKTS, duration, interval),
        (DEVICE_STATE_IF2_RX_PKTS, duration, interval),
    ])
    LOGGER.info('results:\n{:s}'.format(', '.join(map(str, results))))
    assert len(results) == 4
    for result in results: assert isinstance(result, bool) and result

    stored_config = device_driverapi_emulated.GetConfig()
    LOGGER.info('stored_config:\n{:s}'.format('\n'.join(map(str, stored_config))))
    device_config_if2 = list(filter(lambda row: '10.2.0.1' not in row[0], copy.deepcopy(DEVICE_CONFIG_IF2)))
    assert len(stored_config) == len(DEVICE_CONFIG_ENDPOINTS) + len(DEVICE_CONFIG_IF1) + len(device_config_if2)
    for config_row in stored_config:
        assert (config_row in DEVICE_CONFIG_ENDPOINTS) or (config_row in DEVICE_CONFIG_IF1) or \
            (config_row in device_config_if2)
    for config_row in DEVICE_CONFIG_ENDPOINTS: assert config_row in stored_config
    for config_row in DEVICE_CONFIG_IF1: assert config_row in stored_config
    for config_row in device_config_if2: assert config_row in stored_config
