#ifndef MOTION_STATE_MACHINE_H_
#define MOTION_STATE_MACHINE_H_

#include <Arduino.h>
#include <hardware/timer.h>
#include <hardware/irq.h>

#define MOTION_MODE_POS           0
#define MOTION_MODE_VEL           1
#define MOTION_MODE_QUEUE         2

// queue (timed block playback) states
#define QS_IDLE       0   // holding still; blocks may be queued, waiting for START_AT
#define QS_ARMED      1   // start time set, waiting for it
#define QS_RUNNING    2   // playing blocks
#define QS_UNDERRUN   3   // ran out of blocks while moving: decelerating / stopped (sticky)
#define QS_HALTED     4   // halted by command: decelerating / stopped (sticky)

// START_AT result codes
#define QSTART_OK         0
#define QSTART_EMPTY      1   // nothing queued
#define QSTART_PAST       2   // start time already passed
#define QSTART_BUSY       3   // already armed/running, or still moving
#define QSTART_MOVED      4   // motor moved since the first block was queued (HALT to clear)
#define QSTART_NOCLOCK    5   // machine clock not locked to USB SOF

#define MOTION_QUEUE_LEN  64

typedef struct motionState_t {
  float pos;
  float vel;
  float accel;
  bool is_moving;
  uint64_t time_ns;   // machine time at which pos/vel/accel were computed
} motionState_t;

typedef struct motionQueueState_t {
  uint8_t state;
  uint16_t free;
  uint32_t blocks_done;
  uint64_t now_ns;
  uint16_t isr_max_us;  // worst integrator ISR duration since last read
} motionQueueState_t;

void motion_init(uint32_t microsecondsPerIntegration);

void motion_integrate(void);
void alarm_dt_handler(void);

void motion_setPositionTarget(float target, float maxVel, float maxAccel);
void motion_setVelocityTarget(float target, float maxAccel);
void motion_setPosition(float pos);

void motion_getCurrentStates(motionState_t* statePtr);

// ---- timed block queue
// machine time: the shared timeline blocks are scheduled on (ns)
uint64_t motion_machineTimeNs(void);
// append one block; start position/velocity chain from the previous block (or
// from the current position when the queue is empty and idle).
// p_end is 16.16 fixed point full steps, velocities in steps/s. false if full.
bool motion_queueBlock(uint32_t duration_ns, int64_t p_end, float v_start, float v_end);
uint16_t motion_queueFree(void);
// begin playback at machine time t_ns; haltAccel (steps/s^2) is used to stop on underrun
uint8_t motion_queueStartAt(uint64_t t_ns, float haltAccel);
// clear the queue and decelerate to a stop
void motion_halt(float decel);
void motion_getQueueState(motionQueueState_t* q);

#endif
