#include "pin.h"
#include "registers.h"
#include <stdlib.h>

void pin_init(pin_t* pin, GPIO_TypeDef *gpio, uint8_t pin_index) {
  pin->gpio = gpio;
  pin->pin = pin_index;
}

void pin_mode(pin_t *pin, pin_mode_t mode) {
  reg_write_bits_pos(&pin->gpio->MODER, (uint32_t)mode, pin->pin << 1, 0b11);
}
void pin_pull(pin_t *pin, pin_pullmode_t mode) {
  reg_write_bits_pos(&pin->gpio->PUPDR, (uint32_t)mode, pin->pin << 1, 0b11);
}
void pin_speed(pin_t *pin, pin_speedmode_t mode) {
  reg_write_bits_pos(&pin->gpio->OSPEEDR, (uint32_t)mode, pin->pin << 1, 0b11);
}

uint8_t pin_read(pin_t *pin) {
  reg_read_bits_pos(&pin->gpio->IDR, pin->pin, 1);
}

uint8_t pin_write(pin_t *pin, uint8_t val) {
  reg_write_bits_pos(&pin->gpio->ODR, val, pin->pin, 1);
}
void pin_toggle(pin_t *pin) {
  reg_toggle_bits_pos(&pin->gpio->ODR, pin->pin, 1);
}
void pin_set(pin_t *pin) {
  pin->gpio->BSRR = 1 << pin->pin;
}
void pin_reset(pin_t *pin) {
  pin->gpio->BSRR = 1 << (pin->pin + GPIO_BSRR_BR0_Pos);
}

void pin_into_output(pin_t *pin) {
  pin_mode(pin, OUTPUT);
}
void pin_into_output_pushpull(pin_t *pin) {
  pin_into_output(pin);
  pin_into_pushpull(pin);
}
void pin_into_output_opendrain(pin_t *pin) {
  pin_into_output(pin);
  pin_into_opendrain(pin);
}

void pin_into_pushpull(pin_t *pin) {
  reg_write_bits_pos(&pin->gpio->OTYPER, 0, pin->pin, 1);
}
void pin_into_opendrain(pin_t *pin) {
  reg_write_bits_pos(&pin->gpio->OTYPER, 1, pin->pin, 1);
}

void pin_into_input(pin_t *pin) {
  pin_mode(pin, INPUT);
}
void pin_into_input_highspeed(pin_t *pin) {
  pin_into_input(pin);
  pin_into_highspeed(pin);
}

void pin_into_alternate(pin_t *pin, uint8_t alternate) {
  pin_mode(pin, ALTERNATE);
  pin_pull(pin, NONE);
  uint8_t index = pin->pin >> 3;
  uint8_t pos = (pin->pin & 0x7) * 4;
  volatile uint32_t *afr = pin->gpio->AFR;
  reg_write_bits_pos(afr + index, alternate, pos, 0xF);
}
void pin_into_alternate_highspeed(pin_t *pin, uint8_t alternate) {
  pin_into_alternate(pin, alternate);
  pin_into_highspeed(pin);
}

void pin_into_highspeed(pin_t *pin) {
  pin_speed(pin, VERY_HIGH_SPEED);
}
