const std = @import("std");
const microzig = @import("microzig");
const rp2xxx = microzig.hal;
const time = rp2xxx.time;

const LOW = 0;
const HIGH = 1;
const BOUNCE_DELAY = 20;

// Compile-time pin configuration
const pin_config = rp2xxx.pins.GlobalConfiguration{
    .GPIO15 = .{
        .name = "red_led",
        .direction = .out,
    },
    .GPIO16 = .{
        .name = "blue_led",
        .direction = .out,
    },
    .GPIO17 = .{
        .name = "green_led",
        .direction = .out,
    },
    .GPIO13 = .{
        .name = "button",
        .direction = .in,
    },
};

var ledState: bool = false;

const pins = pin_config.pins();

pub fn main() !void {
    pin_config.apply();

    while (true) {
        if (pins.button.read() == HIGH) {
            // button pressed, let's wait a bit
            time.sleep_ms(BOUNCE_DELAY);
            if (pins.button.read() == LOW) {
                // still pressed, so toggle it
                pins.red_led.toggle();
            }
            // wait until the button release
            while (pins.button.read() == LOW) {
                // just to avoid optimization
                pins.green_led.put(HIGH);
            }
            pins.green_led.put(LOW);
        }
    }

    // while (true) {
    //     if (pins.button.read() == LOW) {
    //         time.sleep_ms(BOUNCE_DELAY);
    //         if (pins.button.read() == LOW) {
    //             reverseGPIO();
    //         }
    //         while (pins.button.read() == LOW) {
    //             // zig optimizez away the loop in ReleaseSmall
    //             // if nothing happens here :-(
    //             // pins.green_led.put(HIGH);
    //         }
    //         // pins.green_led.put(LOW);
    //     }

    //     if (ledState) {
    //         pins.red_led.put(HIGH);
    //         pins.blue_led.put(LOW);
    //     } else {
    //         pins.red_led.put(LOW);
    //         pins.blue_led.put(HIGH);
    //     }
    // }
}

fn reverseGPIO() void {
    ledState = !ledState;
    // pins.led.put(@intFromBool(ledState));
}