/*
 Copyright 2019 Florian Dold

 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 test from "ava";
import { MemoryBackend } from "./MemoryBackend.js";
import { BridgeIDBDatabase, BridgeIDBFactory } from "./bridge-idb.js";
import { promiseFromRequest, promiseFromTransaction } from "./idbpromutil.js";

test("export", async (t) => {
  const backend = new MemoryBackend();
  const idb = new BridgeIDBFactory(backend);

  const request = idb.open("library", 42);
  request.onupgradeneeded = () => {
    const db = request.result;
    const store = db.createObjectStore("books", { keyPath: "isbn" });
    const titleIndex = store.createIndex("by_title", "title", { unique: true });
    const authorIndex = store.createIndex("by_author", "author");
  };

  const db: BridgeIDBDatabase = await promiseFromRequest(request);

  const tx = db.transaction("books", "readwrite");
  tx.oncomplete = () => {
    console.log("oncomplete called");
  };

  const store = tx.objectStore("books");

  store.put({ title: "Quarry Memories", author: "Fred", isbn: 123456 });
  store.put({ title: "Water Buffaloes", author: "Fred", isbn: 234567 });
  store.put({ title: "Bedrock Nights", author: "Barney", isbn: 345678 });

  await promiseFromTransaction(tx);

  const exportedData = backend.exportDump();
  const backend2 = new MemoryBackend();
  backend2.importDump(exportedData);
  const exportedData2 = backend2.exportDump();

  t.assert(
    exportedData.databases["library"].objectStores["books"].records.length ===
      3,
  );
  t.deepEqual(exportedData, exportedData2);

  t.is(exportedData.databases["library"].schema.databaseVersion, 42);
  t.is(exportedData2.databases["library"].schema.databaseVersion, 42);
  t.pass();
});
