#pragma once
#include "StreamingMsgPackEncoder.h"
#include "FilesystemAbstraction.h"

#ifdef USE_ESP32 

struct WriterAdaptor 
{
    File * f;
    void write(const char * ptr, size_t size) {
        f->write(reinterpret_cast<const uint8_t *>(ptr), size);
    }
};

class SpiffsStorageWriter {
public:
    SpiffsStorageWriter(const String &fileName) :
            f_(SPIFFS.open(fileName, "w")),
            adaptor_{&f_},
            encoder_(&adaptor_),
            fileName_(fileName)
    {
        bool success = f_;
        Serial.println(success);
    }
    ~SpiffsStorageWriter() {
        f_.close();
        Serial.println(fileName_);
        Serial.println(SPIFFS.exists(fileName_));
    }
    StreamingMsgPackEncoder<WriterAdaptor> &encoder() { return encoder_; }

private:
    File f_;
    WriterAdaptor adaptor_;
    StreamingMsgPackEncoder<WriterAdaptor> encoder_;
    String fileName_;
};

#else 

class SpiffsStorageWriter {
public:
    SpiffsStorageWriter(const String &fileName) :
            f_(SPIFFS.open(fileName, "w")),
            encoder_(&f_),
            fileName_(fileName)
    {
        bool success = f_;
        Serial.println(success);
    }
    ~SpiffsStorageWriter() {
        f_.close();
        Serial.println(fileName_);
        Serial.println(SPIFFS.exists(fileName_));
    }
    StreamingMsgPackEncoder<File> &encoder() { return encoder_; }

private:
    File f_;
    StreamingMsgPackEncoder<File> encoder_;
    String fileName_;
};

#endif





class SpiffsStorageReader
{
public:
    SpiffsStorageReader(const String &fileName) :
            f_(SPIFFS.open(fileName, "r"))
    {}
    ~SpiffsStorageReader() {
        f_.close();
    }

    uint32_t readBytes(char *buffer, size_t length) {
        return f_.readBytes(buffer, length);
    }

    bool seek(uint32_t pos) {
        return f_.seek(pos);
    }
private:
    File f_;
};