#include "button.h"
#include "multi_button.h"

#include "drivers/chip/gpio.h"
#include "os/os.h"

#define CONFIG_SYS_LOG_LEVEL SYS_LOG_LEVEL_WRN
#define SYS_LOG_DOMAIN "BUTTON"
#include "sys_log.h"

static os_work_t s_work_hdl;

static uint8_t _port_pin_level(uint8_t button_id);
static void _work_handler_button(void *pvParameter);

/**
 * @brief 添加一个按键
 *
 * @param pin           引脚配置
 * @param cb            回调函数
 * @param event_mask    触发事件源。 @ref EVENT_MASK
 * @retval handler
 */
button_hdl_t *btn_attach(const cfg_board_pin_io_t *pin,
                         button_callback_fn cb,
                         uint8_t event_mask)
{
    button_hdl_t *handle = os_malloc(sizeof(button_hdl_t));
    if (handle == NULL)
    {
        SYS_LOG_WRN("operation fail");
        return NULL;
    }

    drv_gpio_pin_configure(pin->pin, _GPIO_DIR_IN, pin->en_lev ? _GPIO_PUD_PULL_DOWN : _GPIO_PUD_PULL_UP);

    button_init(handle, _port_pin_level, pin->en_lev, pin->pin);
    button_attach(handle, event_mask, cb);
    button_start(handle);

    os_work_create_default(&s_work_hdl, "", _work_handler_button, NULL, OS_PRIORITY_HIGHEST, 10);

    return 0;
}

void btn_delete(button_hdl_t *handler)
{
    if (handler)
    {
        button_stop(handler);
        os_free(handler);
    }
}

press_event_t btn_get_event(button_hdl_t *handle)
{
    return get_button_event(handle);
}

static void _work_handler_button(void *pvParameter)
{
    os_work_later(TICKS_INTERVAL);
    button_ticks();
}

static uint8_t _port_pin_level(uint8_t button_id)
{
    return drv_gpio_pin_read(button_id);
}
