#define BTSTACK_FILE__ "hog_avrcp_demo.c"

// *****************************************************************************
/* EXAMPLE_START(hog_avrcp_demo): HID avrcp LE
 */
// *****************************************************************************

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>

#include "hog_avrcp_demo.h"
#include "hog_avrcp.h"
#include "btstack.h"
#include "omw_config.h"
#include "ble/gatt-service/battery_service_server.h"
#include "ble/gatt-service/device_information_service_server.h"
#include "ble/gatt-service/hids_device.h"
//
#define MIN_CONN_INTERVAL 210   //  (MIN_CONN_INTERVAL * 1.25ms)
#define MAX_CONN_INTERVAL 220   //  (MAX_CONN_INTERVAL * 1.25ms)
#define SLAVE_LATENCY 0         //
#define SUPERVISION_TIMEOUT 500 //  (SUPERVISION_TIMEOUT * 10ms)
bool paired_enable = false;     // 蓝牙配对是否使能,当配对使能时SM需要等待paired_enable = false

// AVRCP描述符
const uint8_t hid_descriptor_media_control[] = {
    0x05, 0x0C, // USAGE_PAGE (Consumer Devices)
    0x09, 0x01, // USAGE (Consumer Control)
    0xA1, 0x01, // COLLECTION (Application)
    0x85, 0x01, //   REPORT ID (1)

    // Next Track Button
    0x09, 0xB5, //   USAGE (Next Track)
    0x15, 0x00, //   LOGICAL_MINIMUM (0)
    0x25, 0x01, //   LOGICAL_MAXIMUM (1)
    0x75, 0x01, //   REPORT_SIZE (1)
    0x95, 0x01, //   REPORT_COUNT (1)
    0x81, 0x02, //   INPUT (Data,Var,Abs)

    // Previous Track Button
    0x09, 0xB6, //   USAGE (Previous Track)
    0x95, 0x01, //   REPORT_COUNT (1)
    0x81, 0x02, //   INPUT (Data,Var,Abs)

    // Play/Pause Button
    0x09, 0xCD, //   USAGE (Play/Pause)
    0x95, 0x01, //   REPORT_COUNT (1)
    0x81, 0x02, //   INPUT (Data,Var,Abs)

    // Volume Up Button
    0x09, 0xE9, //   USAGE (Volume Up)
    0x95, 0x01, //   REPORT_COUNT (1)
    0x81, 0x02, //   INPUT (Data,Var,Abs)

    // Volume Down Button
    0x09, 0xEA, //   USAGE (Volume Down)
    0x95, 0x01, //   REPORT_COUNT (1)
    0x81, 0x02, //   INPUT (Data,Var,Abs)

    // Padding to fill 1 byte (3 bits unused)
    0x95, 0x03, //   REPORT_COUNT (3)
    0x75, 0x01, //   REPORT_SIZE (1)
    0x81, 0x03, //   INPUT (Cnst,Var,Abs)

    0xC0 // END_COLLECTION
};

static btstack_packet_callback_registration_t hci_event_callback_registration;
static btstack_packet_callback_registration_t l2cap_event_callback_registration;
static btstack_packet_callback_registration_t sm_event_callback_registration;
static uint8_t battery = 100;
static hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
static uint8_t protocol_mode = 1;

static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);

const uint8_t adv_data[] = {
    // Flags general discoverable, BR/EDR not supported
    0x02,
    BLUETOOTH_DATA_TYPE_FLAGS,
    0x06,
    // Name Selfie
    0x0a,
    BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME,
    'H',
    'I',
    'D',
    ' ',
    'S',
    'o',
    'n',
    'g',
    's',
    // 16-bit Service UUIDs: HID Service
    0x03,
    BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS,
    ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE & 0xff,
    ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE >> 8,
    // Appearance: Generic HID
    0x03,
    BLUETOOTH_DATA_TYPE_APPEARANCE,
    0xC0,
    0x03,
};
const uint8_t adv_data_len = sizeof(adv_data);

static void hog_avrcp_setup(void)
{
    // setup l2cap and
    l2cap_init();

    // setup SM: Display only
    sm_init();
    sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
    sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);

    // setup ATT server
    att_server_init(profile_data, NULL, NULL);

    // setup battery service
    battery_service_server_init(battery);

    // setup device information service
    device_information_service_server_init();

    // setup HID Device service
    hids_device_init(0, hid_descriptor_media_control, sizeof(hid_descriptor_media_control));

    // setup advertisements
    uint16_t adv_int_min = 0x0030;
    uint16_t adv_int_max = 0x0030;
    uint8_t adv_type = 0;
    bd_addr_t null_addr;
    memset(null_addr, 0, 6);
    gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
    gap_advertisements_set_data(adv_data_len, (uint8_t *)adv_data);
    gap_advertisements_enable(1);

    // register for events
    hci_event_callback_registration.callback = &packet_handler;
    hci_add_event_handler(&hci_event_callback_registration);

    // register for connection parameter updates
    l2cap_event_callback_registration.callback = &packet_handler;
    l2cap_add_event_handler(&l2cap_event_callback_registration);

    sm_event_callback_registration.callback = &packet_handler;
    sm_add_event_handler(&sm_event_callback_registration);

    hids_device_register_packet_handler(packet_handler);
}

// HID Report sending
static void send_report(uint8_t buttons)
{
    // Create HID report for "Next Track" or "Previous Track"
    uint8_t report[] = {buttons};

    // Send the HID report
    hids_device_send_input_report(con_handle, report, sizeof(report));

    // Print debug message
    switch (buttons)
    {
    case NEXT_TRACK:
        printf("Media Control: Buttons: Next Track (0x01)\n");
        break;
    case PREVIOUS_TRACK:
        printf("Media Control: Buttons: Previous Track (0x02)\n");
        break;
    case PLAY_PAUSE_BUTTON:
        printf("Play/Pause Button: Buttons: Play/Pause Button (0x04)\n");
        break;
    case VOLUME_UP:
        printf("Volume Up Button: Buttons: Play/Pause Button (0x08)\n");
        break;
    case VOLUME_DOWN:
        printf("Volume Down Button: Buttons: Play/Pause Button (0x10)\n");
        break;
    case NO_ACTION:
        printf("Media Control: Buttons: No Action (0x00)\n");
        break;
    default:
        printf("Media Control: Buttons: Unknown (0x%02x)\n", buttons);
        break;
    }
}

static uint8_t buttons;

static void avrcp_can_send_now(void)
{
    send_report(buttons); // 功能键
    send_report(0);       // 释放按键
}

// On embedded systems, simulate clicking on 4 corners of a square

#define AVRCP_PERIOD_MS 3000

static btstack_timer_source_t avrcp_timer;
static int avrcp_active = 0;
static int step;

static void avrcp_timer_handler(btstack_timer_source_t *ts)
{
    if (con_handle == HCI_CON_HANDLE_INVALID)
    {
        avrcp_active = 0;
        return;
    }

    // 模拟切换歌曲

    switch (buttons)
    {
    case NO_ACTION:
        buttons = NEXT_TRACK;
        break;
    case NEXT_TRACK:
        buttons = PREVIOUS_TRACK;
        break;
    case PREVIOUS_TRACK:
        buttons = PLAY_PAUSE_BUTTON;
        break;
    case PLAY_PAUSE_BUTTON:
        buttons = VOLUME_UP;
        break;
    case VOLUME_UP:
        buttons = VOLUME_DOWN;
        break;
    case VOLUME_DOWN:
        buttons = NEXT_TRACK;
        break;
    default:
        buttons = NO_ACTION;
        break;
    }

    // trigger send
    hids_device_request_can_send_now_event(con_handle);

    // set next timer
    btstack_run_loop_set_timer(ts, AVRCP_PERIOD_MS);
    btstack_run_loop_add_timer(ts);
}

static void hid_embedded_start_avrcp(void)
{
    if (avrcp_active)
        return;
    avrcp_active = 1;

    printf("Start AVRCP..\n");

    step = 0;

    // set one-shot timer
    avrcp_timer.process = &avrcp_timer_handler;
    btstack_run_loop_set_timer(&avrcp_timer, AVRCP_PERIOD_MS);
    btstack_run_loop_add_timer(&avrcp_timer);
}

static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
{
    UNUSED(channel);
    UNUSED(size);
    uint16_t conn_interval = 0;
    static bool change_connection_parameter_flag = false;

    if (packet_type != HCI_EVENT_PACKET)
        return;

    switch (hci_event_packet_get_type(packet))
    {
    case HCI_EVENT_DISCONNECTION_COMPLETE:
        con_handle = HCI_CON_HANDLE_INVALID;
        printf("Disconnected\n");
//        set_ble_paired_disable();
        break;
    case SM_EVENT_JUST_WORKS_REQUEST:
        printf("Just Works requested\n");
        sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
        break;
    case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
        printf("Confirming numeric comparison: %" PRIu32 "\n", sm_event_numeric_comparison_request_get_passkey(packet));
        sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
        break;
    case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
        printf("Display Passkey: %" PRIu32 "\n", sm_event_passkey_display_number_get_passkey(packet));
        break;
    case L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE:
        printf("L2CAP Connection Parameter Update Complete, response: %x\n", l2cap_event_connection_parameter_update_response_get_result(packet));
        set_ble_paired_disable();
        break;
    case HCI_EVENT_META_GAP:
        switch (hci_event_gap_meta_get_subevent_code(packet))
        {
        case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
            // get con_handle
            con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
            conn_interval = gap_subevent_le_connection_complete_get_conn_interval(packet);
            printf("LE Connection Complete:\n");
            printf("- Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
            printf("- Connection Latency: %u\n", gap_subevent_le_connection_complete_get_conn_latency(packet));
            // 广播模式下请求较长的连接间隔
            if ((con_handle != HCI_CON_HANDLE_INVALID) && (paired_enable == true))
            {
                change_connection_parameter_flag = true;
                gap_request_connection_parameter_update(con_handle, MIN_CONN_INTERVAL, MAX_CONN_INTERVAL, SLAVE_LATENCY, SUPERVISION_TIMEOUT);
                printf("Change Connection Parameter\n");
            }
            break;
        default:
            break;
        }
        break;
    case HCI_EVENT_LE_META:
        switch (hci_event_le_meta_get_subevent_code(packet))
        {
        case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
            // print connection parameters (without using float operations)
            conn_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
            printf("LE Connection Update:\n");
            printf("- Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
            printf("- Connection Latency: %u\n", hci_subevent_le_connection_update_complete_get_conn_latency(packet));
            set_ble_paired_disable();
            break;
        default:
            break;
        }
        break;
    case HCI_EVENT_HIDS_META:
        switch (hci_event_hids_meta_get_subevent_code(packet))
        {
        case HIDS_SUBEVENT_INPUT_REPORT_ENABLE:
            con_handle = hids_subevent_input_report_enable_get_con_handle(packet);
            printf("Report Characteristic Subscribed %u\n", hids_subevent_input_report_enable_get_enable(packet));
            //  当配对完成后将连接间隔缩短
            if (con_handle != HCI_CON_HANDLE_INVALID)
            {
                if (change_connection_parameter_flag)
                {
                    change_connection_parameter_flag = false;
                    gap_request_connection_parameter_update(con_handle, 16, 16, SLAVE_LATENCY, SUPERVISION_TIMEOUT);
                    printf("Change Connection Parameter\n");
                }
            }
            // #ifndef HAVE_BTSTACK_STDIN
            //  hid_embedded_start_avrcp();
            // #endif

            // request connection param update via L2CAP following Apple Bluetooth Design Guidelines
            // gap_request_connection_parameter_update(con_handle, 12, 12, 4, 100);  // 15 ms, 4, 1s
            // directly update connection params via HCI following Apple Bluetooth Design Guidelines
            // gap_update_connection_parameters(con_handle, 12, 12, 4, 100);    // 60-75 ms, 4, 1s

            break;
        case HIDS_SUBEVENT_BOOT_KEYBOARD_INPUT_REPORT_ENABLE:
            con_handle = hids_subevent_boot_keyboard_input_report_enable_get_con_handle(packet);
            printf("Boot Keyboard Characteristic Subscribed %u\n", hids_subevent_boot_keyboard_input_report_enable_get_enable(packet));
            break;
        case HIDS_SUBEVENT_BOOT_MOUSE_INPUT_REPORT_ENABLE:
            con_handle = hids_subevent_boot_mouse_input_report_enable_get_con_handle(packet);
            printf("Boot Mouse Characteristic Subscribed %u\n", hids_subevent_boot_mouse_input_report_enable_get_enable(packet));
            break;
        case HIDS_SUBEVENT_PROTOCOL_MODE:
            protocol_mode = hids_subevent_protocol_mode_get_protocol_mode(packet);
            printf("Protocol Mode: %s mode\n", hids_subevent_protocol_mode_get_protocol_mode(packet) ? "Report" : "Boot");
            break;
        case HIDS_SUBEVENT_CAN_SEND_NOW:
            avrcp_can_send_now();
            break;
        default:
            break;
        }
        break;

    default:
        break;
    }
}

/**
 * @brief trigger send
 *
 * @param send_data NO_ACTION 0x00
 * NEXT_TRACK 0x01
 * PREVIOUS_TRACK 0x02
 * PLAY_PAUSE_BUTTON 0x04
 * VOLUME_UP 0x08
 * VOLUME_DOWN 0x10
 */
void arvcp_key_trigger_send(uint8_t send_data)
{
    if (con_handle == HCI_CON_HANDLE_INVALID)
    {
        return;
    }

    buttons = send_data;

    hids_device_request_can_send_now_event(con_handle);
}

/**
 * @brief
 *
 * @return true 连接
 * @return false 未连接
 */
uint16_t arvcp_get_con_handle(void)
{
    return con_handle;
}

bool get_paired_enable_flag(void){
    return paired_enable;
}

void set_ble_paired_enable(void)
{
    paired_enable = true;
}

void set_ble_paired_disable(void)
{
    paired_enable = false;
}

int btstack_main(void);
int btstack_main(void)
{
    hog_avrcp_setup();

#ifdef HAVE_BTSTACK_STDIN
    btstack_stdin_setup(stdin_process);
#endif

    // turn on!
    hci_power_control(HCI_POWER_ON);

    return 0;
}
