#include <array>

#include "virtual_timer/VirtualTimerDistributor.h"

#include "platform/cm4/InterruptHandler.h"
#include "platform/cm4/InterruptGuardian.h"
#include "platform/cm4/SystemTick.h"

#include "platform/nrf52/gpio.h"
#include "platform/nrf52/gpiote.h"
#include "platform/nrf52/InterruptHandler.h"
#include "platform/nrf52/InterruptGuardian.h"

#include "gpio_interface.h"
#include "delay.h"

using namespace pinetime::platform;
using namespace pinetime::virtual_timer;

// IRQs
nrf52::InterruptGuardian nrf52::InterruptGuardian::instance;
cm4::InterruptGuardian cm4::InterruptGuardian::instance;

// GPIO events
nrf52::Gpiote gpiote;

// Timer
cm4::SystemTick system_tick;
VirtualTimerDistributor virtual_timer_distributor(system_tick.instance());
pinetime::Delay delay;


enum {
    PIN_NUMBER_BUTTON_1 = 13,
    PIN_NUMBER_BUTTON_2 = 14,
    PIN_NUMBER_BUTTON_3 = 15,
    PIN_NUMBER_BUTTON_4 = 16,
    PIN_NUMBER_LED_1 = 17,
    PIN_NUMBER_LED_2 = 18,
    PIN_NUMBER_LED_3 = 19,
    PIN_NUMBER_LED_4 = 20
};

// LEDs
nrf52::Gpio led_1(PIN_NUMBER_LED_1);
nrf52::Gpio led_2(PIN_NUMBER_LED_2);
nrf52::Gpio led_3(PIN_NUMBER_LED_3);
nrf52::Gpio led_4(PIN_NUMBER_LED_4);
std::array<nrf52::Gpio *, 4> leds = {&led_1, &led_2, &led_3, &led_4};

// Buttons
nrf52::Gpio button_1(PIN_NUMBER_BUTTON_1);
nrf52::Gpio button_2(PIN_NUMBER_BUTTON_2);
nrf52::Gpio button_3(PIN_NUMBER_BUTTON_3);
nrf52::Gpio button_4(PIN_NUMBER_BUTTON_4);

int main(void)
{
    button_1.set_direction(pinetime::interfaces::GpioInterface::direction::IN, true);
    cm4::InterruptGuardian::enable_interrupts();
    while(true) {
        for(auto it = leds.begin(); it != leds.end(); ++it) {
            uint32_t b1 = button_1.get();
            if(b1) {
                nrf52::Gpio * led = *it;
                led->toggle();
            }
        }
    }
    return 0;
}
