#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO

// System Includes
#include <Arduino.h>
#include <DebugLog.h>
#include <string>
#include <fstream>
#include <ArduinoJson.h>
#include <filesystem>
#include <LittleFS.h>

// Project Includes
#include "isr.h"
#include "psvector.h"

const uint32_t max_history = 256;
const bool SAVE_HISTORY_TO_LITTLEFS = false; // Set to true to enable saving history to LittleFS, false to disable
static bool first_save = true;               // flag to indicate if this is the first save (to write header)

struct dataSaveParams
{
    const PSRAMVector<ignitionBoxStatus> *history;
    const std::filesystem::path file_path;
};

class LITTLEFSGuard
{
public:
    LITTLEFSGuard();
    ~LITTLEFSGuard();
};

class ignitionBoxStatusAverage
{
private:
    ignitionBoxStatus m_last;
    uint32_t m_count = 0;
    uint32_t m_max_count = 100; // number of samples to average before resetting
    bool m_data_valid = false;  // flag to indicate if the average data is valid (i.e. at least one sample has been added)

public:
    ignitionBoxStatusAverage() = default;
    ignitionBoxStatusAverage(const uint32_t max_count) : m_max_count(max_count)
    {
        m_data_valid = false;
        m_count = 0;
    }

    void reset();
    void update(const ignitionBoxStatus &new_status);
    const bool get(ignitionBoxStatus &status) const;
    const ArduinoJson::JsonDocument toJson() const;

private:
    void filter(int32_t &old, const int32_t value, const uint32_t k);
    void filter(float &old, const float value, const uint32_t k);
};

// Task and function declarations
void saveHistoryTask(void *pvParameters);
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path &file_path);
