#ifndef NEWDB_H
#define NEWDB_H

#include <memory>
#include <unordered_set>
#include <mutex>
#include <thread>
#include "leveldb/db.h"
#include "db/log_writer.h"

namespace leveldb{

class LEVELDB_EXPORT NewDB {
  public:
  NewDB() = default;

  NewDB(const NewDB&) = delete;
  NewDB& operator=(const NewDB&) = delete;

  virtual ~NewDB();

  std::string SerializeValue(const FieldArray& fields);    
  FieldArray ParseValue(const std::string& value_str);    
  std::string ConstructIndexKey(const Slice& key, const Field& field);
  std::string ExtractIndexKey(const Slice& key);
  std::string ConstructRecoverKey(std::string UserOpID, std::string TinyOpID, std::string DBname);
  std::string ConstructRecoverValue(std::string TinyOp, std::string key, std::string value);
  std::string ExtractRecoverKey(std::string s);
  std::pair<std::string, std::string> ExtractRecoverValue(std::string s, std::string* TinyOp);
  std::string ConstructUserOpID(std::thread::id thread_id);

  static Status Open(const Options& options, const std::string& name,
                      NewDB** dbptr);  // 改为返回 NewDB* 类型-橙

  Status Put_fields(const WriteOptions& options, const Slice& key,
                     const FieldArray& fields);
                    
  std::pair<FieldArray, FieldArray> UpdateIndex(const WriteOptions& options, const Slice& key, 
                const FieldArray& fields, const FieldArray& current_fields);


  Status Get_fields(const ReadOptions& options, const Slice& key,   
                     FieldArray* fields);

  bool Delete(const WriteOptions& options, const Slice& key);

  std::vector<std::string> FindKeysByField(Field &field);

  // std::string ConstructKey(const Slice& key, const Field& field);

  // std::string ExtractKey(const Slice& key);

  bool CreateIndexOnField(const std::string& field_name);

  std::vector<std::string> QueryByIndex(Field &field);

  bool DeleteIndex(const std::string& field_name);
  
  // 用于存储已经为其创建索引的字段名称。只有当字段名在这个集合中时，才会在 indexDB 中插入对应的索引条目。
  std::unordered_set<std::string> indexed_fields_read;
  std::unordered_set<std::string> indexed_fields_write;

  std::unordered_set<std::string> putting_keys;

  private:
  std::unique_ptr<DB> data_db_;

  std::unique_ptr<DB> index_db_;

  std::unique_ptr<DB> recover_db_;

  std::mutex db_mutex_;  // 用于跨数据库操作的互斥锁

  uint64_t TinyOpID;
};

}

#endif