#include "pico/stdlib.h"
#include "pico/time.h"

const uint LED_PIN = 11;
const uint BUTTON_PIN = 5;
const uint BUTTON_PIN2 = 7;

volatile int cont_bot = 0;
volatile bool button2_pressed = false;
bool led_active = false;

int64_t turn_off_callback(alarm_id_t id, void *user_data) {
    gpio_put(LED_PIN, false);
    cont_bot = 0;
    button2_pressed = false;
    led_active = false;
    return 0;
}

int main() {
    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, GPIO_OUT);
    gpio_init(BUTTON_PIN);
    gpio_set_dir(BUTTON_PIN, GPIO_IN);
    gpio_pull_up(BUTTON_PIN);
    gpio_init(BUTTON_PIN2);
    gpio_set_dir(BUTTON_PIN2, GPIO_IN);
    gpio_pull_up(BUTTON_PIN2);

    while (true) {

        if (gpio_get(BUTTON_PIN) == 0 && !led_active) {
            sleep_ms(50);  // Debounce
            if (gpio_get(BUTTON_PIN) == 0) { 
                cont_bot++;
                sleep_ms(50);
            }
        }


        if (gpio_get(BUTTON_PIN2) == 0) {
            sleep_ms(50);  // Debounce
            if (gpio_get(BUTTON_PIN2) == 0) {  
                button2_pressed = true;
            }
        }


        if (cont_bot == 5 && !led_active) {
            led_active = true;
            add_alarm_in_ms(10000, turn_off_callback, NULL, false);  // Agenda desligamento após 10s

            if (button2_pressed) {
                // Pisca o LED a 1 Hz (1 vez por segundo)
                for (int i = 0; i < 10; i++) {
                    gpio_put(LED_PIN, true);
                    sleep_ms(500);
                    gpio_put(LED_PIN, false);
                    sleep_ms(500);
                }
            } else {
                // Pisca o LED a 10 Hz (10 vezes por segundo)
                for (int i = 0; i < (10000 / 100); i++) {
                    gpio_put(LED_PIN, true);
                    sleep_ms(50);
                    gpio_put(LED_PIN, false);
                    sleep_ms(50);
                }
            }
        }
        sleep_ms(10);
    }

    return 0;
}