#include <stdio.h>
#include "pico/stdlib.h"

#define LED_BLUE_PIN 12
#define BUTTON_A_PIN 5

#define DEBOUNCE_DELAY_MS 50
#define BLINK_DURATION_MS 10000
#define BLINK_FREQUENCY_HZ 10

bool button_a_state = false;
int button_a_count = 0;

bool debounce(uint pin, bool *last_state) {
    static uint32_t last_time = 0;
    uint32_t current_time = to_ms_since_boot(get_absolute_time());
    bool current_state = gpio_get(pin) == 0;

    if (current_state != *last_state) {
        if (current_time - last_time > DEBOUNCE_DELAY_MS) {
            last_time = current_time;
            *last_state = current_state;
            return current_state;
        }
    }
    return *last_state;
}

int main() {
    stdio_init_all();

    gpio_init(BUTTON_A_PIN);
    gpio_set_dir(BUTTON_A_PIN, GPIO_IN);
    gpio_pull_up(BUTTON_A_PIN);

    gpio_init(LED_BLUE_PIN);
    gpio_set_dir(LED_BLUE_PIN, GPIO_OUT);
    gpio_put(LED_BLUE_PIN, false);

    while (true) {
        bool button_a_pressed = debounce(BUTTON_A_PIN, &button_a_state);

        if (button_a_pressed) {
            button_a_count++;
            printf("Botao A pressionado %d vezes\n", button_a_count);
        }

        if (button_a_count >= 5) {
            button_a_count = 0;
            uint32_t blink_start_time = to_ms_since_boot(get_absolute_time());
            while (to_ms_since_boot(get_absolute_time()) - blink_start_time < BLINK_DURATION_MS) {
                gpio_put(LED_BLUE_PIN, 1);
                sleep_ms(1000 / (2 * BLINK_FREQUENCY_HZ));
                gpio_put(LED_BLUE_PIN, 0);
                sleep_ms(1000 / (2 * BLINK_FREQUENCY_HZ));
            }
            gpio_put(LED_BLUE_PIN, 0);
        }

        sleep_ms(100);
    }

    return 0;
}