import { Client } from "memjs";
const memcached = Client.create("localhost:41211");

const DB_NAME = "Memcached";

const N1 = 2000;
const N2 = 300;

const region1Enemies = ["1", "2", "3", "11", "12", "13", "14"];
const region1Items = ["1", "8", "21", "26"];

const playerObj = (i: number) => ({
  id: 1,
  name: "Jonas",
  health: 50 + (i % 50),
  stamina: 50 + (i % 50),
  level: 1 + (i % 20),
  region_id: 1,
});

const enemyObj = { id: 0, name: "Benchmark Enemy", health: 1000, level: 20, damage: 50 };
const itemObj = { id: 0, name: "Benchmark Item", gear_type: "weapon", gear_id: 1 };
const regionObj = { id: 1, name: "Limgrave" };

async function getJson(key: string): Promise<any> {
  const { value } = await memcached.get(key);
  return value ? JSON.parse(value.toString()) : null;
}

async function setJson(key: string, value: any) {
  await memcached.set(key, JSON.stringify(value), {});
}

async function writeSingle(i: number) {
  await setJson("bench:player:1", playerObj(i));
}

async function readSingle(_i: number) {
  await getJson("bench:player:1");
}

async function readRegion(_i: number) {
  const region = await getJson("region:1");
  void region?.name;
  const enemyIds = (await getJson("region:1:enemies")) || [];
  const itemIds = (await getJson("region:1:items")) || [];
  for (const id of enemyIds) await getJson(`enemy:${id}`);
  for (const id of itemIds) await getJson(`item:${id}`);
}

async function writeRegion(_i: number) {
  await setJson("bench:region:1", regionObj);
  await setJson("bench:region:1:enemies", region1Enemies);
  await setJson("bench:region:1:items", region1Items);
  for (const id of region1Enemies) await setJson(`bench:enemy:${id}`, { ...enemyObj, id });
  for (const id of region1Items) await setJson(`bench:item:${id}`, { ...itemObj, id });
}

async function timed(label: string, group: string, iters: number, opsPerIter: number, fn: (i: number) => Promise<void>) {
  const warmup = Math.min(50, iters);
  for (let i = 0; i < warmup; i++) await fn(i);
  const start = performance.now();
  for (let i = 0; i < iters; i++) await fn(i);
  const ms = performance.now() - start;
  const totalOps = iters * opsPerIter;
  const opsPerSec = totalOps / (ms / 1000);
  const avgMs = ms / totalOps;
  return { label, group, iters, opsPerIter, totalOps, ms, opsPerSec, avgMs };
}

function fmt(r: any) {
  return `  ${r.label.padEnd(11)} | ${String(r.totalOps).padStart(6)} Ops | ${r.ms.toFixed(1).padStart(9)} ms | ${Math.round(r.opsPerSec).toString().padStart(9)} Ops/s | ${r.avgMs.toFixed(4)} ms/Op`;
}

await memcached.set("__ping__", "1", {});

const w1 = await timed("Schreiben", "Anwendungsfall 1: Live-Player-Sync (1 Schluessel)", N1, 1, writeSingle);
const r1 = await timed("Lesen", "Anwendungsfall 1: Live-Player-Sync (1 Schluessel)", N1, 1, readSingle);
const r2 = await timed("Lesen", "Anwendungsfall 2: Region laden / Fast Travel (14 Schluessel)", N2, 14, readRegion);
const w2 = await timed("Schreiben", "Anwendungsfall 2: Region laden / Fast Travel (14 Schluessel)", N2, 14, writeRegion);

console.log(`\n===== Benchmark: ${DB_NAME} =====`);
console.log(w1.group);
console.log(fmt(w1));
console.log(fmt(r1));
console.log(r2.group);
console.log(fmt(r2));
console.log(fmt(w2));

console.log("##RESULT## " + JSON.stringify({ db: DB_NAME, tests: [w1, r1, r2, w2] }));
process.exit(0);
