#include "touch_btn.h"
#include "FreeRTOS.h"
#include "task.h"

typedef struct
{
    uint8_t id;
    bool last_pressed;
    bool current_pressed;
    uint32_t press_start_time;
    touchBtn_event_t event;
} TouchBtn_t;

static TouchBtn_t btns[NUM_BTNS] =
{
{ 0, false, false, 0, TOUCH_NONE },
  { 1, false, false, 0, TOUCH_NONE } };

static uint64_t button_status = 0;

// 外部变量，由 qe_touch_callback 设置
extern volatile uint8_t g_qe_touch_flag;

void TouchBtn_Init(void)
{
    RM_TOUCH_Open (g_qe_touch_instance_config01.p_ctrl, g_qe_touch_instance_config01.p_cfg);
    RM_TOUCH_ScanStart (g_qe_touch_instance_config01.p_ctrl);
}

void TouchBtn_Process(void)
{
    RM_TOUCH_ScanStart (g_qe_touch_instance_config01.p_ctrl);
    if (!g_qe_touch_flag)
        return;

    g_qe_touch_flag = 0;

    if (RM_TOUCH_DataGet (g_qe_touch_instance_config01.p_ctrl, &button_status, NULL, NULL) != FSP_SUCCESS)
        return;

//    uint32_t now = get_system_time_ms ();
    uint32_t now = xTaskGetTickCount();

    for (int i = 0; i < NUM_BTNS; i++)
    {
        TouchBtn_t *btn = &btns[i];
        btn->last_pressed = btn->current_pressed;
        btn->current_pressed = (button_status & (1ULL << btn->id)) != 0;

        if (!btn->last_pressed && btn->current_pressed)
        {
            // 新按下，记录开始时间
            btn->press_start_time = now;
            btn->event = TOUCH_NONE;
        }
        else if (btn->current_pressed)
        {
            // 持续按住中
            uint32_t duration = now - btn->press_start_time;
            if (duration >= LONG_PRESS_THRESHOLD_MS && btn->event != TOUCH_LONG_PRESS)
            {
                btn->event = TOUCH_LONG_PRESS;
            }
        }
        else if (btn->last_pressed && !btn->current_pressed)
        {
            // 松手时判断是否为短按（未达到长按阈值时）
            uint32_t duration = now - btn->press_start_time;
            if (duration < LONG_PRESS_THRESHOLD_MS)
            {
                btn->event = TOUCH_SHORT_PRESS;
            }
        }
    }
}

touchBtn_event_t TouchBtn_GetEvent(uint8_t btn_id)
{
    if (btn_id >= NUM_BTNS)
        return TOUCH_NONE;

    touchBtn_event_t e = btns[btn_id].event;
    btns[btn_id].event = TOUCH_NONE;
    return e;
}
