#ifndef STORAGE_LEVELDB_DB_VLOG_MANAGER_H_
#define STORAGE_LEVELDB_DB_VLOG_MANAGER_H_
#include <unordered_map>
#include <cstdint>
#include "leveldb/env.h"
#include "db/filename.h"
#include "leveldb/options.h"


namespace leveldb{
class SequentialFile;
namespace vlog{
class  VlogManager{
    public:
    VlogManager() = default;
    ~VlogManager() = default;
    //Add a vlog file, vlog file is already exist.
    void AddVlogFile(uint64_t vlogfile_number, SequentialFile* seq_file, WritableFile* write_file);
    SequentialFile* GetVlogFile(uint64_t vlogfile_number);
    bool IsEmpty();
    void MarkVlogValueInvalid(uint64_t vlogfile_number, uint64_t offset);

    SequentialFile* GetSequentialFile(WritableFile* write_file) {
        auto it = writable_to_sequential_.find(write_file);
        return it != writable_to_sequential_.end() ? it->second : nullptr;
    }

    void IncrementTotalValueCount(WritableFile* write_file) {
        auto seq_file = GetSequentialFile(write_file);
        if (seq_file) {
            seq_file->IncrementTotalValueCount(); // 假设 SequentialFile 提供该方法
        }
    }

    void CleanupInvalidVlogFiles(const Options& options, const std::string& dbname) {
        for (const auto& vlog_pair : vlog_table_) {
            uint64_t vlogfile_number = vlog_pair.first;
            auto vlog_file = vlog_pair.second;
            
            if (vlog_file->AllValuesInvalid()) { // 检查文件内所有值是否无效
                RemoveVlogFile(vlogfile_number, options, dbname); // 删除 VLog 文件
            }
        }
    }

    void RemoveVlogFile(uint64_t vlogfile_number, const Options& options, const std::string& dbname) {  // 移除无效的vlogfile文件
        auto it = vlog_table_.find(vlogfile_number);
        if (it != vlog_table_.end()) {
            delete it->second; // 删除对应的 SequentialFile
            vlog_table_.erase(it); // 从管理器中移除
            options.env->DeleteFile(VlogFileName(dbname, vlogfile_number)); // 删除实际文件
        }
    }

   private:
    std::unordered_map<uint64_t, SequentialFile*> vlog_table_; // 用映射组织vlog文件号和文件的关系
    std::unordered_map<WritableFile*, SequentialFile*> writable_to_sequential_;
};   
}// namespace vlog
}
#endif
