import gdb
from freertos.List import ListManager, get_list_container
import json


def get_freertos_timers(config, types):
    if config.use_timers:
        timer1 = ListManager("xActiveTimerList1", types)
        timer2 = ListManager("xActiveTimerList2", types)
        result = []

        for tcb, val in timer1.get_elements(types.timer_type):
            result.append(__prepare_timer_data(tcb))
    
        for tcb, val in timer2.get_elements(types.timer_type):
            result.append(__prepare_timer_data(tcb))
    
        return json.dumps(result)
    else:
        return "[]"


def __prepare_timer_data(timer):  # : gdb.Value, : str
    # Bit definitions used in the ucStatus member of a timer structure.
    # define tmrSTATUS_IS_ACTIVE                  ( ( uint8_t ) 0x01 )
    # define tmrSTATUS_IS_STATICALLY_ALLOCATED    ( ( uint8_t ) 0x02 )
    # define tmrSTATUS_IS_AUTORELOAD              ( ( uint8_t ) 0x04 )
    status = []
    try:
        if timer['ucStatus'] & 0x01 != 0:
            status.append("Active")
        if timer['ucStatus'] & 0x02 != 0:
            status.append("Static")
        if timer['ucStatus'] & 0x04 != 0:
            status.append("Autoreload")
    except gdb.error:
        # FreeRTOS V10.1.1-
        if get_list_container(timer['xTimerListItem']) != 0:
            status.append("Active")
        try:
            if timer['ucStaticallyAllocated'] != 0:
                status.append("Static")
        except gdb.error:
            pass
        if timer['uxAutoReload'] != 0:
            status.append("Autoreload")

    return {
      'name': timer['pcTimerName'].string(),
      'id': int(timer['pvTimerID']),
      'period': int(timer['xTimerPeriodInTicks']),
      'status': ' '.join(status),
      'callback': str(timer['pxCallbackFunction'])
    }
