import time


def is_entry_added_to_table(switch_inst, table_name, srch_params, timeout=1, expect_count=1, exist=True):
    """Check if entry with specified fields values is added to table

    Args:
        switch_inst(object):  Switch instance to work with
        table_name(str):  The name of table to perform search in
        srch_params(dict):  Parameters for entry search
        timeout(int):  Time to wait
        expect_count(int):  Number of entries in the table that correspond to search parameters (integer)
        exist(bool):  Decided if entry exists in table or not (boolean)

    Returns:
        bool: True/False

    Examples::

        srch_params = {'macAddress': '00:00:00:BB:00:AA', 'portId': 24, 'valid': 'Enabled'}
        assert helpers.is_entry_added_to_table(env.switch[1], "DcbxRemotes", srch_params, timeout=5)
        assert helpers.is_entry_added_to_table(env.switch[1], "DcbxRemotes", srch_params, timeout=5, exist=False)

    """
    end_time = time.time() + timeout
    while True:
        # Calculate number of entry occurrences in table
        table = switch_inst.getprop_table(table_name)
        occur_count = 0
        for row in table:
            if all([row[field] == value for field, value in srch_params.items()]):
                occur_count += 1

        return_value = False
        if exist:
            if occur_count == expect_count:
                return_value = True
        else:
            if not occur_count:
                return_value = True

        # Exit while loop if entry is added to table or due to timeout expiration
        if return_value or time.time() > end_time:
            break
        else:
            time.sleep(0.5)

    return return_value