#include "user_inputs.h"

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

void HAL_GPIO_EXTI_Callback(uint16_t pin) {
  Event ev;

  GPIO_PinState state = HAL_GPIO_ReadPin(GPIOB, pin);
  ev.type = state;
  switch (pin) {
  case BTN0_Pin:
    ev.type = EV_BTN_PRESS;
    ev.btn_press = BTN_PRESS_PREV;
    break;
  case BTN1_Pin:
    ev.type = EV_BTN_PRESS;
    ev.btn_press = BTN_PRESS_R2D;
    break;
  case BTN2_Pin:
    ev.type = EV_BTN_PRESS;
    ev.btn_press = BTN_PRESS_OK;
    break;
  case BTN3_Pin:
    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:
    stw_state.view_state.ami.current_mission =
        stw_state.view_state.mission_select.selection;
    stw_state.view = VIEW_AMI;
    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;
  }
  }
}