/*
 * timeouts.h
 *
 *  Created on: May 29, 2025
 *      Author: herli
 */

#ifndef INC_TIMEOUTS_H_
#define INC_TIMEOUTS_H_

#include "main.h"  // for uint16_t etc.
#include <stdbool.h>

extern uint32_t BitStatus;

extern volatile float RPM;
extern float PHI_AD;
extern float ME;
extern uint8_t forceDC;
extern uint8_t safetySHUTOFF;
extern uint8_t startup;
extern volatile uint8_t startedEngine;
extern uint8_t CKP_PULSE_AVAILABLE;
extern uint8_t captorOK;
extern uint8_t maxTeeth;

typedef void (*TimeoutCallback)(void);  // Define a function pointer type

typedef struct {
	uint8_t enabled;
    uint16_t* last_tick_ptr;      // Pointer to externally updated tick
    uint16_t timeout_duration;    // Timeout in timer ticks (e.g., 500 = 50ms)
    uint32_t* status_bit_ptr;      // Pointer to byte holding status flag
    uint16_t bit_mask;             // Bit mask to set if timeout occurred
    uint8_t inverted;
    TimeoutCallback on_timeout;     // Callback function (can be NULL)
    uint8_t started;
} TimeoutEntry;


uint8_t has_timed_out(uint16_t start, uint16_t duration);
void CheckTimeouts(uint16_t current_time, TimeoutEntry* timeouts);
void Timeout_Reset(uint16_t* tick_ptr, uint16_t new_tick, uint16_t* status_ptr, uint16_t bit_mask);
void Timeout_ResetByIndex(uint8_t index, uint16_t new_tick);
void Timeout_ResetByIndexNoStatus(uint8_t index, uint16_t new_tick);
void Set_Timeout_Period_ByIndex(uint8_t index, uint16_t period);
bool Timeout_IsStarted(uint8_t index);
extern void Timeout_StartIfStopped(uint8_t index, uint16_t now);
bool Timeout_HasElapsed(uint8_t index, uint16_t now);  // uses entry’s own duration


void Timeout_StopByIndex(uint8_t index);

uint16_t* Timeout_GetCanTickPtr(void);
uint16_t* Timeout_GetIcRPMTickPtr(void);
uint16_t* Timeout_GetTurnOffTickPtr(void);


void Timeout_CheckAll(uint16_t current_time);  // shortcut
void Timeout_PollActions(void);
#endif /* INC_TIMEOUTS_H_ */
