//int errorcode[2] = {0,0}; 1 Bit per error
#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 {    // valid transitions: (all could transition to error)
  STATE_INACTIVE,       // INACTIVE   ->  PRECHARGE, CHARGING, ERROR  
  STATE_PRECHARGE,      // PRECHARGE  ->  INACTIVE, READY, DISCHARGE, ERROR
  STATE_READY,          // READY      ->  ACTIVE, DISCHARGE, ERROR
  STATE_ACTIVE,         // ACTIVE     ->  READY, DISCHARGE, ERROR
  STATE_DISCHARGE,      // DISCHARGE  ->  INACTIVE, PRECHARGE, ERROR
  STATE_CHARGING,       // CHARGING   ->  INACTIVE, DISCHARGE, ERROR
  STATE_ERROR,          // ERROR      ->  INACTIVE, DISCHARGE, ERROR
} State;
  
typedef struct {
  uint16_t bms_timeout : 1;
  uint16_t overtemp : 1;
  uint16_t overcurrent : 1;
  uint16_t overvoltage : 1;
  uint16_t missing_current_reading : 1;
  uint16_t missing_voltage_reading : 1;
  uint16_t missing_temp_reading : 1;
  uint16_t precharge_fail : 1;
  uint16_t powerground_fail : 1;
} ErrorKind;

//typedef enum {} WarningKind;

typedef struct {
  State current_state;
  State target_state;
  uint16_t error_source; // TSErrorSource (bitmask)
  ErrorKind error_type; // TSErrorKind
} StateHandle;

extern StateHandle state;

void sm_init();
void sm_update();

State sm_update_inactive();
State sm_update_precharge();
State sm_update_ready();
State sm_update_active();
State sm_update_discharge();
State sm_update_charging();
State sm_update_error();

typedef enum { RELAY_MAIN, RELAY_PRECHARGE } Relay;
void sm_set_relay_positions(State state);
void sm_set_relay(Relay relay, bool closed);
void sm_check_precharge_discharge(int *is_closed, int should_close);

void sm_handle_ams_in(const uint8_t *data);

void sm_set_error(ErrorKind error_kind, bool is_errored);