/*
 Copyright 2024 Taler Systems S.A.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 or implied. See the License for the specific language governing
 permissions and limitations under the License.
 */

import * as fs from "node:fs";
import {
  BridgeIDBDatabase,
  BridgeIDBFactory,
  BridgeIDBRequest,
  BridgeIDBTransaction,
  createSqliteBackend,
} from "./index.js";
import { createNodeHelperSqlite3Impl } from "./node-helper-sqlite3-impl.js";

function openDb(idbFactory: BridgeIDBFactory): Promise<BridgeIDBDatabase> {
  return new Promise((resolve, reject) => {
    const openReq = idbFactory.open("mydb", 1);
    openReq.addEventListener("success", () => {
      const database = openReq.result;
      resolve(database);
    });
    openReq.addEventListener("upgradeneeded", (event: any) => {
      const database: BridgeIDBDatabase = event.target.result;
      const transaction: BridgeIDBTransaction = event.target.transaction;
      database.createObjectStore("books", {
        keyPath: "isbn",
      });
    });
  });
}

function requestToPromise(req: BridgeIDBRequest): Promise<any> {
  //const stack = Error("Failed request was started here.");
  return new Promise((resolve, reject) => {
    req.onsuccess = () => {
      resolve(req.result);
    };
    req.onerror = () => {
      console.error("error in DB request", req.error);
      reject(req.error);
      //console.error("Request failed:", stack);
    };
  });
}

function transactionToPromise(tx: BridgeIDBTransaction): Promise<void> {
  //const stack = Error("Failed request was started here.");
  return new Promise((resolve, reject) => {
    tx.addEventListener("complete", () => {
      resolve();
    });
    tx.onerror = () => {
      console.error("error in DB txn", tx.error);
      reject(tx.error);
      //console.error("Request failed:", stack);
    };
  });
}

const nTx = Number(process.argv[2]);
const nInsert = Number(process.argv[3]);

async function main() {
  const filename = "mytestdb.sqlite3";
  try {
    fs.unlinkSync(filename);
  } catch (e) {
    // Do nothing.
  }

  console.log(`doing ${nTx} iterations of ${nInsert} items`);

  const sqlite3Impl = await createNodeHelperSqlite3Impl();
  const backend = await createSqliteBackend(sqlite3Impl, {
    filename,
  });
  backend.enableTracing = false;
  const idbFactory = new BridgeIDBFactory(backend);
  const db = await openDb(idbFactory);

  for (let i = 0; i < nTx; i++) {
    const tx = db.transaction(["books"], "readwrite");
    const txProm = transactionToPromise(tx);
    const books = tx.objectStore("books");
    for (let j = 0; j < nInsert; j++) {
      const addReq = books.add({
        isbn: `${i}-${j}`,
        name: `book-${i}-${j}`,
      });
      await requestToPromise(addReq);
    }
    await txProm;
  }

  console.log("done");
}

main();
