import json


def update_error_message(chart_data_json_str, acq_state, hat_selection,
                         active_channels):
    """
    A callback function to display error messages.

    Args:
        chart_data_json_str (str): A string representation of a JSON object
            containing the current chart data - triggers the callback.
        acq_state (str): The application state of "idle", "configured",
            "running" or "error" - triggers the callback.
        hat_selection (str): A string representation of a JSON object
            containing the descriptor for the selected MCC 134 DAQ HAT.
        active_channels ([int]): A list of integers corresponding to the user
            selected Active channel checkboxes.

    Returns:
        str: The error message to display.
    """
    error_message = ''
    if acq_state == 'running':
        chart_data = json.loads(chart_data_json_str)
        if ('open_tc_error' in chart_data.keys()
                and chart_data['open_tc_error']):
            error_message += 'Open thermocouple; '
        if ('over_range_error' in chart_data.keys()
                and chart_data['over_range_error']):
            error_message += 'Temp outside valid range; '
        if ('common_mode_range_error' in chart_data.keys()
                and chart_data['common_mode_range_error']):
            error_message += 'Temp outside common-mode range; '
    elif acq_state == 'error':
        num_active_channels = len(active_channels)
        if not hat_selection:
            error_message += 'Invalid HAT selection; '
        if num_active_channels <= 0:
            error_message += 'Invalid channel selection (min 1); '

    return error_message