#include <stdint.h>
#include "ql_api_osi.h"
#include "ql_api_spi.h"
// #include "cfg.h"
#include "ql_log.h"

#define LOGD(msg, ...) QL_LOG(QL_LOG_LEVEL_DEBUG, "soft_enc", msg, ##__VA_ARGS__)
#define LOGI(msg, ...) QL_LOG(QL_LOG_LEVEL_INFO, "soft_enc", msg, ##__VA_ARGS__)
#define LOGW(msg, ...) QL_LOG(QL_LOG_LEVEL_WARN, "soft_enc", msg, ##__VA_ARGS__)
#define LOGE(msg, ...) QL_LOG(QL_LOG_LEVEL_ERROR, "soft_enc", msg, ##__VA_ARGS__)

extern uint16_t gWordVar[];
int enc_value = 0;
static int last_edge_a = 0;
static int last_edge_b = 0;

static void soft_enc_a_gpio(void *ctx)
{
    // LOGI("gpio_mcp_int_cb");
    ql_LvlMode gpio_lvl;
    ql_gpio_get_level(GPIO_2, &gpio_lvl);
    if (last_edge_b)
    {
        last_edge_b = 0;
        if (gpio_lvl == 1)
        {
            enc_value++;
        }
        else
        {
            enc_value--;
        }
    }
    last_edge_a = 1;
}
static void soft_enc_b_gpio(void *ctx)
{
    // LOGI("gpio_mcp_int_cb");
    ql_LvlMode gpio_lvl;
    ql_gpio_get_level(GPIO_0, &gpio_lvl);
    if (last_edge_a)
    {
        last_edge_a = 0;
        if (gpio_lvl == 0)
        {
            enc_value++;
        }
        else
        {
            enc_value--;
        }
    }
    last_edge_b = 1;
}
void soft_enc_init(void)
{
    int ret;
    ret = ql_pin_set_func(66, 1); // set pin 66 to gpio0
    if (ret != QL_GPIO_SUCCESS)
    {
        LOGE("ql_pin_set_func 66 err ret=%d", ret);
    }
    ret = ql_int_register(GPIO_0, EDGE_TRIGGER, DEBOUNCE_EN, EDGE_FALLING, PULL_UP, soft_enc_a_gpio, NULL);
    if (ret != QL_GPIO_SUCCESS)
    {
        LOGE("ql_int_register GPIO_0 err ret=%d", ret);
    }
    ret = ql_pin_set_func(67, 1); // set pin 67 to gpio2
    if (ret != QL_GPIO_SUCCESS)
    {
        LOGE("ql_pin_set_func 67 err ret=%d", ret);
    }
    ret = ql_int_register(GPIO_2, EDGE_TRIGGER, DEBOUNCE_EN, EDGE_FALLING, PULL_UP, soft_enc_b_gpio, NULL);
    if (ret != QL_GPIO_SUCCESS)
    {
        LOGE("ql_int_register GPIO_2 err ret=%d", ret);
    }
    ql_int_enable(GPIO_0);
    ql_int_enable(GPIO_2);
}