#include <leveldb/db.h>
#include "leveldb/env.h"
#include <leveldb/options.h>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include "gtest/gtest.h"

using namespace leveldb;
using Field = std::pair<std::string, std::string>; // field_name:field_value
using FieldArray = std::vector<std::pair<std::string, std::string>>;

// 序列化为字符串
std::string SerializeValue(const FieldArray& fields) {
  std::ostringstream oss;
  for (const auto& field : fields) {
    oss << field.first << ":" << field.second << ";";
  }
  return oss.str();
}

// 反序列化为字段数组
FieldArray ParseValue(const std::string& value_str) {
  FieldArray fields;
  std::istringstream iss(value_str);
  std::string field_str;
  while (std::getline(iss, field_str, ';')) {
    size_t delimiter_pos = field_str.find(':');
    if (delimiter_pos != std::string::npos) {
      std::string field_name = field_str.substr(0, delimiter_pos);
      std::string field_value = field_str.substr(delimiter_pos + 1);
      fields.emplace_back(field_name, field_value);
    }
  }
  return fields;
}

// 根据字段值查找所有包含该字段的 key
std::vector<std::string> FindKeysByField(leveldb::DB* db, Field &field) {
  std::vector<std::string> keys;
  leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());

  for (it->SeekToFirst(); it->Valid(); it->Next()) {
    std::string key = it->key().ToString();
    std::string value;
    db->Get(leveldb::ReadOptions(), key, &value);

    FieldArray fields = ParseValue(value);
    for (const auto& f : fields) {
      if (f.first == field.first && f.second == field.second) {
        keys.push_back(key);
        break; // 假设每个key中每个字段值唯一，如果允许重复，可以移除这行
      }
    }
  }

  delete it;
  return keys;
}

Status OpenDB(std::string dbName, DB **db) {
  Options options;
  options.create_if_missing = true;
  return DB::Open(options, dbName, db);
}

TEST(TestSchema, Basic) {
  DB *db;
  WriteOptions writeOptions;
  ReadOptions readOptions;
  if(OpenDB("testdb", &db).ok() == false) {
    std::cerr << "open db failed" << std::endl;
    abort();
  }
  std::string key1 = "k_1";
  std::string key2 = "k_2";
  FieldArray fields1 = {
      {"name", "Customer#000000001"},
      {"address", "IVhzIApeRb"},
      {"phone", "25-989-741-2988"}
  };

  FieldArray fields2 = {
      {"name", "Customer#000000001"},
      {"address", "ecnu"},
      {"phone", "123456789"}
  };
  // 序列化并插入
  std::string value1 = SerializeValue(fields1);
  std::string value2 = SerializeValue(fields2);
  db->Put(leveldb::WriteOptions(), key1, value1);
  db->Put(leveldb::WriteOptions(), key2, value2);

  // 读取并反序列化
  std::string value_ret;
  db->Get(leveldb::ReadOptions(), key1, &value_ret);
  auto fields_ret = ParseValue(value_ret);

  // 检查反序列化结果
  ASSERT_EQ(fields_ret.size(), fields1.size());
  for (size_t i = 0; i < fields_ret.size(); ++i) {
    ASSERT_EQ(fields_ret[i].first, fields1[i].first);
    ASSERT_EQ(fields_ret[i].second, fields1[i].second);
  }

  // 测试查找功能
  Field query_field = {"name", "Customer#000000001"};
  std::vector<std::string> found_keys = FindKeysByField(db, query_field);
  std::cout << "找到的key有：" << found_keys.size() << "个" << std::endl;
  ASSERT_EQ(found_keys[0], key1);

  // 关闭数据库
  delete db;
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}