#include "user_inputs.h"

#include "events.h"
#include "main.h"
#include "state.h"
#include "vehicle.h"

#include "stm32g4xx_hal.h"
#include "stm32g4xx_hal_gpio.h"

#include <stdint.h>

#define MIN_PRESS_INTERVAL 100

void HAL_GPIO_EXTI_Callback(uint16_t pin) {
  static uint32_t last_presses[4] = {0, 0, 0, 0};

  Event ev;

  GPIO_PinState state = HAL_GPIO_ReadPin(GPIOB, pin);
  ev.type = state;
  uint32_t now = HAL_GetTick();
  switch (pin) {
  case BTN0_Pin: {
    if (now - last_presses[0] < MIN_PRESS_INTERVAL) {
      return;
    }
    last_presses[0] = now;
    ev.type = EV_BTN_PRESS;
    ev.btn_press = BTN_PRESS_PREV;
    break;
  }
  case BTN1_Pin: {
    if (now - last_presses[1] < MIN_PRESS_INTERVAL) {
      return;
    }
    last_presses[1] = now;
    ev.type = EV_BTN_PRESS;
    ev.btn_press = BTN_PRESS_R2D;
    break;
  }
  case BTN2_Pin: {
    if (now - last_presses[2] < MIN_PRESS_INTERVAL) {
      return;
    }
    last_presses[2] = now;
    ev.type = EV_BTN_PRESS;
    ev.btn_press = BTN_PRESS_OK;
    break;
  }
  case BTN3_Pin: {
    if (now - last_presses[3] < MIN_PRESS_INTERVAL) {
      return;
    }
    last_presses[3] = now;
    ev.type = EV_BTN_PRESS;
    ev.btn_press = BTN_PRESS_NEXT;
    break;
  }
  default:
    Error_Handler();
  }

  event_push(&ev);
}

void handle_button_press(const ButtonPressEvent* ev) {
  switch (stw_state.view) {
  case VIEW_MISSION_SELECT:
    handle_button_press_mission_select(ev);
    break;
  case VIEW_AMI:
    break;
  default:
    Error_Handler();
  }
}

void handle_button_press_mission_select(const ButtonPressEvent* ev) {
  switch (*ev) {
  case BTN_PRESS_PREV: {
    Mission* selection = &stw_state.view_state.mission_select.selection;
    if (*selection == MISSION_ACCELERATION || *selection == MISSION_NONE) {
      *selection = MISSION_MANUAL;
    } else {
      *selection = *selection - 1;
    }
    break;
  }
  case BTN_PRESS_R2D:
    break;
  case BTN_PRESS_OK:
    vehicle_send_mission_select(stw_state.view_state.mission_select.selection);
    break;
  case BTN_PRESS_NEXT: {
    Mission* selection = &stw_state.view_state.mission_select.selection;
    if (*selection == MISSION_MANUAL) {
      *selection = MISSION_ACCELERATION;
    } else {
      *selection = *selection + 1;
    }
    break;
  }
  }
}

ButtonsState get_buttons_state() {
  ButtonsState result;
  result.left = HAL_GPIO_ReadPin(BTN0_GPIO_Port, BTN0_Pin);
  result.right = HAL_GPIO_ReadPin(BTN3_GPIO_Port, BTN3_Pin);
  result.r2d = HAL_GPIO_ReadPin(BTN1_GPIO_Port, BTN1_Pin);
  result.enter = HAL_GPIO_ReadPin(BTN2_GPIO_Port, BTN2_Pin);
  result.enc0a = HAL_GPIO_ReadPin(ENC0A_GPIO_Port, ENC0A_Pin);
  result.enc0b = HAL_GPIO_ReadPin(ENC0B_GPIO_Port, ENC0B_Pin);
  result.enc1a = HAL_GPIO_ReadPin(ENC1A_GPIO_Port, ENC1A_Pin);
  result.enc1b = HAL_GPIO_ReadPin(ENC1B_GPIO_Port, ENC1B_Pin);
  return result;
}
