// SPDX-License-Identifier: Apache-2.0
#include <tactility/device.h>
#include <tactility/drivers/keyboard.h>
#include <tactility/error.h>

#define KEYBOARD_DRIVER_API(driver) ((struct KeyboardApi*)driver->api)

extern "C" {

error_t keyboard_read_key(Device* device, KeyboardKeyData* data) {
    const auto* driver = device_get_driver(device);

    // Default the modifier/HID fields here rather than in each driver: only drivers whose hardware
    // can report them set them, and the rest would otherwise leave whatever the caller's stack held.
    data->ctrl = false;
    data->alt = false;
    data->hid_keycode = 0;
    data->hid_modifier = 0;

    return KEYBOARD_DRIVER_API(driver)->read_key(device, data);
}

error_t keyboard_get_backlight(Device* device, Device** backlight_device) {
    const auto* driver = device_get_driver(device);

    if (KEYBOARD_DRIVER_API(driver)->get_backlight == nullptr) {
        return ERROR_NOT_SUPPORTED;
    }

    return KEYBOARD_DRIVER_API(driver)->get_backlight(device, backlight_device);
}

bool keyboard_is_present(Device* device) {
    const auto* driver = device_get_driver(device);

    if (KEYBOARD_DRIVER_API(driver)->is_present == nullptr) {
        return true;
    }

    return KEYBOARD_DRIVER_API(driver)->is_present(device);
}

const DeviceType KEYBOARD_TYPE {
    .name = "keyboard"
};

}
