#include "avrcp_key.h"
static btstack_timer_source_t avrcp_key_timer;
#define AVRCP_KEY_PERIOD_MS 40
#define DOUBLE_CLICK_INTERVAL_MS 250         // 双击最大时间间隔
#define SLEEP_INTERVA_MS 10000               // 未连接状态下SLEEP_INTERVA_MS时间内按键未操作进入休眠
#define PAIRED_ENABLE_SLEEP_INTERVA_MS 60000 // 开启配对模式后等待较长时间再进入休眠

#define HIGH_LEVEL 1
#define LOW_LEVEL 0

#define NUMBER_OF_KEYS 4

#define SINGLE_CLICK 0x01
#define DOUBLE_CLICK 0x02
#define LONG_PRESS 0x04

// 定义按键回调函数类型
typedef void (*avrcp_key_callback)(uint8_t function);

// 定义按键结构体
typedef struct
{
    const char *name;                // 按键名称
    uint8_t pin;                     // 按键引脚
    uint8_t function;                // 按键功能 bit0:SINGLE_CLICK bit1:DOUBLE_CLICK bit2:LONG_PRESS
    uint8_t previous_key_state;      // 上次按键状态(默认都为高电平)
    uint8_t current_key_state;       // 当前按键状态
    uint8_t click_count;             // 点击计数器
    uint8_t long_press_conut;        // 长按计数器long_press_conut*AVRCP_KEY_PERIOD_MS=long_press_time
    uint16_t long_press_time;        // 长按long_press_time触发长按事件
    uint32_t last_click_time;        // 上次点击时间
    avrcp_key_callback key_callback; // 按键回调函数
} avrcp_key_t;

static uint16_t sleep_count = 0;
static uint8_t avrcp_device_run_mode = NOT_CONNECTED_MODE;
static uint16_t avrcp_device_con_handle = HCI_CON_HANDLE_INVALID;

void key1_callback(uint8_t function)
{
    switch (function)
    {
    case SINGLE_CLICK:
        arvcp_key_trigger_send(NEXT_TRACK);
        break;
    case LONG_PRESS:
        hci_send_cmd(&hci_disconnect, avrcp_device_con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
        gap_advertisements_enable(1);
        set_ble_paired_enable();
        break;
    default:
        break;
    }
    sleep_count = 0;
    if (avrcp_device_run_mode == SLEEP_MODE)
    {
        avrcp_device_run_mode = NOT_CONNECTED_MODE;
        gap_advertisements_enable(1);
    }
}
void key2_callback(uint8_t function)
{
    arvcp_key_trigger_send(PREVIOUS_TRACK);
    sleep_count = 0;
    if (avrcp_device_run_mode == SLEEP_MODE)
    {
        avrcp_device_run_mode = NOT_CONNECTED_MODE;
        gap_advertisements_enable(1);
    }
}
void key3_callback(uint8_t function)
{
    arvcp_key_trigger_send(VOLUME_UP);
    sleep_count = 0;
    if (avrcp_device_run_mode == SLEEP_MODE)
    {
        avrcp_device_run_mode = NOT_CONNECTED_MODE;
        gap_advertisements_enable(1);
    }
}
void key4_callback(uint8_t function)
{
    switch (function)
    {
    case SINGLE_CLICK:
        arvcp_key_trigger_send(VOLUME_DOWN);
        break;
    case DOUBLE_CLICK:
        arvcp_key_trigger_send(PLAY_PAUSE_BUTTON);
        break;
    default:
        break;
    }
    sleep_count = 0;
    if (avrcp_device_run_mode == SLEEP_MODE)
    {
        avrcp_device_run_mode = NOT_CONNECTED_MODE;
        gap_advertisements_enable(1);
    }
}
uint8_t app_can_sleep = 0; // 0不启用休眠 1启用休眠

uint8_t omw_app_can_sleep(void)
{
    return app_can_sleep;
}

avrcp_key_t avrcp_key[NUMBER_OF_KEYS] = {
    {"Key 1", OMW_GPIO_PIN6, SINGLE_CLICK | LONG_PRESS, HIGH_LEVEL, LOW_LEVEL, 0, 0, 3000, 0, key1_callback},
    {"Key 2", OMW_GPIO_PIN7, SINGLE_CLICK, HIGH_LEVEL, LOW_LEVEL, 0, 0, 0, 0, key2_callback},
    {"Key 3", OMW_GPIO_PIN8, SINGLE_CLICK, HIGH_LEVEL, LOW_LEVEL, 0, 0, 0, 0, key3_callback},
    {"Key 4", OMW_GPIO_PIN9, SINGLE_CLICK | DOUBLE_CLICK, HIGH_LEVEL, LOW_LEVEL, 0, 0, 0, 0, key4_callback}};

/**
 * @brief 更新设备运行模式
 *
 * @param key_press_flag
 */
void avrcp_key_run_mode_process(bool key_press_flag)
{
    // 获取连接状态
    avrcp_device_con_handle = arvcp_get_con_handle();

    // 判断连接状态
    if (avrcp_device_con_handle == HCI_CON_HANDLE_INVALID)
    {
        // 未连接状态
        switch (avrcp_device_run_mode)
        {
        case CONNECT_MODE:
            // 修改为未连接模式
            avrcp_device_run_mode = NOT_CONNECTED_MODE;
            break;

        case NOT_CONNECTED_MODE:
            // 增加未连接计数
            sleep_count++;
            if (get_paired_enable_flag())
            {
                if (sleep_count * AVRCP_KEY_PERIOD_MS >= PAIRED_ENABLE_SLEEP_INTERVA_MS)
                {
                    // 停止广播，进入睡眠模式
                    gap_advertisements_enable(0);
                    avrcp_device_run_mode = SLEEP_MODE;
                    app_can_sleep = 1;
                    printf("paired_enable_gap_advertisements_disable\n");
                }
            }
            else if (sleep_count * AVRCP_KEY_PERIOD_MS >= SLEEP_INTERVA_MS)
            {
                // 停止广播，进入睡眠模式
                gap_advertisements_enable(0);
                avrcp_device_run_mode = SLEEP_MODE;
                app_can_sleep = 1;
                printf("gap_advertisements_disable\n");
            }
            break;

        case SLEEP_MODE:
            // 如果任一按键按下开启广播
            if (key_press_flag)
            {
                sleep_count = 0;
                avrcp_device_run_mode = NOT_CONNECTED_MODE;
                gap_advertisements_enable(1);
                app_can_sleep = 0;
            }
            break;

        default:
            // printf("Unknown mode\n");
            break;
        }
    }
    else
    {
        // 已连接状态
        if (avrcp_device_run_mode != CONNECT_MODE)
        {
            // 修改为连接模式并重置计数
            avrcp_device_run_mode = CONNECT_MODE;
            sleep_count = 0;
        }
    }
	//任何模式下有按键按下则开启背光闪烁
	if (key_press_flag){
		start_backlight_task();
	}
	
}
static void avrcp_key_timer_handler(btstack_timer_source_t *ts)
{
    bool key_press_flag = false; // 任意一个按键按下
    // 设置下一个定时器
    btstack_run_loop_set_timer(ts, AVRCP_KEY_PERIOD_MS);
    btstack_run_loop_add_timer(ts);

    // 读取当前按键状态
    for (uint8_t i = 0; i < NUMBER_OF_KEYS; i++)
    {
        avrcp_key[i].current_key_state = omw_gpio_read_input_data(avrcp_key[i].pin);
    }

    // 获取当前时间
    uint32_t current_time = btstack_run_loop_get_time_ms();

    // 遍历所有按键
    for (int i = 0; i < NUMBER_OF_KEYS; i++)
    {
        // 按下
        if (avrcp_key[i].previous_key_state == LOW_LEVEL && avrcp_key[i].current_key_state == LOW_LEVEL)
        {
            avrcp_key[i].long_press_conut++;
        }
        // 松开
        else if (avrcp_key[i].previous_key_state == LOW_LEVEL && avrcp_key[i].current_key_state == HIGH_LEVEL)
        {
            avrcp_key[i].click_count++;                  // 记录按键按下的次数
            avrcp_key[i].last_click_time = current_time; // 更新最后一次点击时间
            // 长按事件
            if ((avrcp_key[i].function & LONG_PRESS) &&
                ((avrcp_key[i].long_press_conut * AVRCP_KEY_PERIOD_MS) > avrcp_key[i].long_press_time))
            {
                avrcp_key[i].key_callback(LONG_PRESS);
                avrcp_key[i].click_count = 0;
            }
            avrcp_key[i].long_press_conut = 0;
            key_press_flag = true;
        }
        // 单击/双击逻辑
        if (avrcp_key[i].click_count)
        {
            if (avrcp_key[i].function & DOUBLE_CLICK)
            {
                if (current_time - avrcp_key[i].last_click_time >= DOUBLE_CLICK_INTERVAL_MS)
                {

                    if (avrcp_key[i].click_count == 2)
                    {
                        avrcp_key[i].key_callback(DOUBLE_CLICK);
                    }
                    else
                    {
                        avrcp_key[i].key_callback(SINGLE_CLICK);
                    }
                    avrcp_key[i].click_count = 0;
                }
            }
            else
            {
                avrcp_key[i].key_callback(SINGLE_CLICK);
                avrcp_key[i].click_count = 0;
            }
        }
        // 更新按键的历史状态
        avrcp_key[i].previous_key_state = avrcp_key[i].current_key_state;
    }

    avrcp_key_run_mode_process(key_press_flag);
}

void avrcp_key_init(void)
{
    // set one-shot timer
    avrcp_key_timer.process = &avrcp_key_timer_handler;
    btstack_run_loop_set_timer(&avrcp_key_timer, AVRCP_KEY_PERIOD_MS);
    btstack_run_loop_add_timer(&avrcp_key_timer);

    // Set the key pin to input mode
    for (uint8_t i = 0; i < NUMBER_OF_KEYS; i++)
    {
        omw_gpio_set_func(avrcp_key[i].pin, OMW_GPIO_CFG_VAL(OMW_GPIO_DRIVE_STRENTH3, 0 | OMW_GPIO_MODE_IN_PULL_UP));
    }
}
