#include "platform/nrf52/gpio.h"

extern "C" {
    #include "nrf52.h"
    #include "nrf52_bitfields.h"

    NRF_GPIO_Type *const GPIO_REGS = reinterpret_cast<NRF_GPIO_Type *>(NRF_P0_BASE);
}

using namespace pinetime::platform::nrf52;

Gpio::Gpio(uint32_t pin)
    : pin_number(pin)
{
    this->set_direction(direction::OUT);
    this->clear();
}

void Gpio::set_direction(direction dir)
{
    uint32_t direct = GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos;
    uint32_t input = GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos;
    uint32_t pull = GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos;
    uint32_t drive = GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos;
    uint32_t sense = GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos;
    if(dir == direction::IN) {
        direct = GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos;
        input = GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos;

        // FIXME: Make this configurable
        // GPIO_PIN_CNF_PULL_Disabled, ///<  Pin pull-up resistor disabled.
        // GPIO_PIN_CNF_PULL_Pulldown, ///<  Pin pull-down resistor enabled.
        // GPIO_PIN_CNF_PULL_Pullup,   ///<  Pin pull-up resistor enabled.
        pull = GPIO_PIN_CNF_PULL_Pullup  << GPIO_PIN_CNF_PULL_Pos;
        drive = GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos;
        sense = GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos;
    }
    GPIO_REGS->PIN_CNF[pin_number] = direct | input | pull | drive | sense;
}

void Gpio::set_pin_number(uint32_t pin)
{
    this->pin_number = pin;
}

uint32_t Gpio::get()
{
    uint32_t res = (GPIO_REGS->IN  >> pin_number) & 1UL;
    return res;
}

void Gpio::set()
{
    GPIO_REGS->OUTSET = 1UL << (this->pin_number);
}

void Gpio::clear()
{
    GPIO_REGS->OUTCLR = 1UL << (this->pin_number);
}

void Gpio::toggle()
{
    uint32_t state = GPIO_REGS->OUT;

    GPIO_REGS->OUTSET = (~state & (1UL << (this->pin_number)));
    GPIO_REGS->OUTCLR = (state & (1UL << (this->pin_number)));
}