#include "key.h"
#include "gpio.h"
#include "multi_button.h"

struct Button *btn_press;

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

key_button_t key_button;

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

uint8_t 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(GPIO_KEY_UP_PORT, GPIO_KEY_UP_PIN);
    case 1:
        return GPIO_ReadInputDataBit(GPIO_KEY0_PORT, GPIO_KEY0_PIN);
    case 2:
        return GPIO_ReadInputDataBit(GPIO_KEY1_PORT, GPIO_KEY1_PIN);
    case 3:
        return GPIO_ReadInputDataBit(GPIO_KEY2_PORT, GPIO_KEY2_PIN);
    default:
        return 0;
    }
}

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

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

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

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