#include "include.h"
#include "wireless_cmd.h"
#include "wireless_service.h"
#include "fota_proc.h"


static struct {
    struct {
        uint8_t type;
        uint8_t length;
        uint8_t value[CTRL_CMD_PACKET_SIZE - 2];
    } cmd_data[CTRL_CMD_PACKET_NUM];
    uint8_t rptr;
    uint8_t wptr;
} wireless_cmd_cb AT(.user_buf.wireless.cmd);


void wireless_user_event_handle(uint8_t *buf, uint32_t size)
{
    switch (buf[WIRELESS_CMD_DATA_TYPE_POS]) {
#if BSP_SDADC_EN
        case WIRELESS_CTRL_CMD_CODE_MIC_DISALLOW:
            bsp_audio_mic_allow_set(false);
            break;

        case WIRELESS_CTRL_CMD_CODE_MIC_ALLOW:
            bsp_audio_mic_allow_set(true);
            break;
#endif // BSP_SDADC_EN

        case WIRELESS_CTRL_CMD_CODE_USB_CONNECTED:
            sys_cb.peer_usb_is_active = 1;
            printf("[CMD] peer usb insert\n");
            break;

        case WIRELESS_CTRL_CMD_CODE_USB_DISCONNECTED:
            sys_cb.peer_usb_is_active = 0;
            printf("[CMD] peer usb remove\n");
            break;

        case WIRELESS_CTRL_CMD_CODE_CAPS_LOCK_CHANGE:
            break;

        default:
            break;
    }
}

AT(.com_text.wireless.cmd.query)
uint8_t wireless_cmd_get_buf(uint8_t *buf)
{
    u8 curr_rptr = wireless_cmd_cb.rptr;
    u8 buf_size;

    if (curr_rptr == wireless_cmd_cb.wptr) {
        return 0;
    }

    buf_size = wireless_cmd_cb.cmd_data[curr_rptr].length + 2;
    memcpy(buf, &wireless_cmd_cb.cmd_data[curr_rptr], buf_size);

    wireless_cmd_cb.rptr = (curr_rptr + 1) % CTRL_CMD_PACKET_NUM;
    return buf_size;
}

/* Not single packet, it will compose with HID or AUDIO */
void wireless_cmd_send_ctrl_command_asyn(uint8_t type, uint8_t length, uint8_t *value)
{
    u8 next_wptr = (wireless_cmd_cb.wptr + 1) % CTRL_CMD_PACKET_NUM;

    if (next_wptr == wireless_cmd_cb.rptr || length > (CTRL_CMD_PACKET_SIZE - 2)) {
        return;
    }

    wireless_cmd_cb.cmd_data[wireless_cmd_cb.wptr].type = type;
    wireless_cmd_cb.cmd_data[wireless_cmd_cb.wptr].length = length;

    if (length && value) {
        memcpy(wireless_cmd_cb.cmd_data[wireless_cmd_cb.wptr].value, value, length);
    }

    wireless_cmd_cb.wptr = next_wptr;
}

void wireless_cmd_init(void)
{
    memset(&wireless_cmd_cb, 0x00, sizeof(wireless_cmd_cb));
}
