#ifndef INC_TS_STATE_MACHINE_H
#define INC_TS_STATE_MACHINE_H

#include "stm32h7xx_hal.h"

#include <stdint.h>
#include <stdbool.h>

// Minimum vehicle side voltage to exit precharge
#define MIN_VEHICLE_SIDE_VOLTAGE 150000 // mV
// Time to wait after reaching 95% of battery voltage before exiting precharge
// Set this to 1000 in scruti to demonstrate the voltage on the multimeter
#define PRECHARGE_95_DURATION 0 // ms
// Time to wait for discharge
#define DISCHARGE_DURATION 5000 // ms
// Time to wait after there is no more error condition before exiting TS_ERROR
#define NO_ERROR_TIME 1000 // ms
// Time to wait for charger voltage before going to TS_ERROR
#define MAX_CHARGING_CHECK_DURATION 2000 // ms
// Time to wait between closing relays
#define RELAY_CLOSE_WAIT 10 // ms

typedef enum {
  TS_INACTIVE,
  TS_ACTIVE,
  TS_PRECHARGE,
  TS_DISCHARGE,
  TS_ERROR,
  TS_CHARGING_CHECK,
  TS_CHARGING
} TSState;

static inline const char *TSStateToString(TSState state) {
  switch (state) {
    case TS_INACTIVE:
      return "INACTIVE";
    case TS_ACTIVE:
      return "ACTIVE";
    case TS_PRECHARGE:
      return "PRECHARGE";
    case TS_DISCHARGE:
      return "DISCHARGE";
    case TS_ERROR:
      return "ERROR";
    case TS_CHARGING_CHECK:
      return "CHARGING_CHECK";
    case TS_CHARGING:
      return "CHARGING";
    default:
      return "INVALID STATE";
  }
}

typedef enum {
  TS_ERRORKIND_NONE = 0x00,
  TS_ERRORKIND_CELL_OVERTEMP = 0x01,
  TS_ERRORKIND_SLAVE_PANIC = 0x02,
  TS_ERRORKIND_SHUNT_TIMEOUT = 0x03,
  TS_ERRORKIND_SHUNT_OVERCURRENT = 0x04,
  TS_ERRORKIND_SHUNT_OVERTEMP = 0x05
} TSErrorKind;

typedef enum {
  TS_ERROR_SOURCE_SHUNT = (1 << 0),
  TS_ERROR_SOURCE_SLAVES = (1 << 1)
} TSErrorSource;

typedef struct {
  TSState current_state;
  TSState target_state;
  uint16_t error_source; // TSErrorSource (bitmask)
  uint16_t error_type; // TSErrorKind
} TSStateHandle;

extern TSStateHandle ts_state;

void ts_sm_init();
void ts_sm_update();

TSState ts_sm_update_inactive();
TSState ts_sm_update_active();
TSState ts_sm_update_precharge();
TSState ts_sm_update_discharge();
TSState ts_sm_update_error();
TSState ts_sm_update_charging_check();
TSState ts_sm_update_charging();

typedef enum { RELAY_NEG, RELAY_POS, RELAY_PRECHARGE } Relay;
void ts_sm_set_relay_positions(TSState state);
void ts_sm_set_relay_position(Relay relay, int closed);
void ts_sm_check_close_wait(int *is_closed, int should_close);

void ts_sm_handle_ams_in(const uint8_t *data);

void ts_sm_set_error_source(TSErrorSource source, TSErrorKind error_type, bool is_errored);

#endif // INC_TS_STATE_MACHINE_H
