#include "dev_key.h"

struct Button *btn_press;

struct Button btn_key_up;
struct Button btn_key0;
struct Button btn_key1;
struct Button btn_key2;

dev_key_t dev_key;

#define KEY_UP_ACTIVE_LEVEL 1
#define KEY0_ACTIVE_LEVEL   0
#define KEY1_ACTIVE_LEVEL   0
#define KEY2_ACTIVE_LEVEL   0

uint8_t dev_key_read_button(uint8_t button_id)
{
    // you can share the GPIO read function with multiple Buttons
    switch (button_id)
    {
    case 0:
        return GPIO_ReadInputDataBit(HAL_GPIO_KEY_UP_PORT, HAL_GPIO_KEY_UP_PIN);
    case 1:
        return GPIO_ReadInputDataBit(HAL_GPIO_KEY0_PORT, HAL_GPIO_KEY0_PIN);
    case 2:
        return GPIO_ReadInputDataBit(HAL_GPIO_KEY1_PORT, HAL_GPIO_KEY1_PIN);
    case 3:
        return GPIO_ReadInputDataBit(HAL_GPIO_KEY2_PORT, HAL_GPIO_KEY2_PIN);
    default:
        return 0;
    }
}

void dev_key_press_down(void *btn)
{
    if (NULL == btn)
    {
        dev_key.i = 0;
    }
    else
    {
        btn_press = (struct Button *)btn;
        if (btn_press == &btn_key_up)
        {
            dev_key.dev_key_state.bits.key_up_state_flag = 1;
        }
        if (btn_press == &btn_key0)
        {
            dev_key.dev_key_state.bits.key0_state_flag = 1;
        }
        if (btn_press == &btn_key1)
        {
            dev_key.dev_key_state.bits.key1_state_flag = 1;
        }
        if (btn_press == &btn_key2)
        {
            dev_key.dev_key_state.bits.key2_state_flag = 1;
        }
    }
}

void dev_key_button_init(void)
{
    button_init(&btn_key_up, dev_key_read_button, KEY_UP_ACTIVE_LEVEL, 0);
    button_init(&btn_key0, dev_key_read_button, KEY0_ACTIVE_LEVEL, 1);
    button_init(&btn_key1, dev_key_read_button, KEY1_ACTIVE_LEVEL, 2);
    button_init(&btn_key2, dev_key_read_button, KEY2_ACTIVE_LEVEL, 3);

    button_attach(&btn_key_up, PRESS_DOWN, dev_key_press_down);
    button_attach(&btn_key0, PRESS_DOWN, dev_key_press_down);
    button_attach(&btn_key1, PRESS_DOWN, dev_key_press_down);
    button_attach(&btn_key2, PRESS_DOWN, dev_key_press_down);

    button_start(&btn_key_up);
    button_start(&btn_key0);
    button_start(&btn_key1);
    button_start(&btn_key2);
}
void dev_key_button_task()
{
    button_ticks();
}
