import { getDcomm, createTests, Matcher } from "./e2etestlib"
import { KeystoreAPI } from "src/apis/keystore/api"
import Dcomm from "src"

describe("Keystore", (): void => {
  const username1: string = "dcommJsUser1"
  const username2: string = "dcommJsUser2"
  const username3: string = "dcommJsUser3"
  const password: string = "dcommJsP1ssw4rd"

  let exportedUser = { value: "" }

  const dcomm: Dcomm = getDcomm()
  const keystore: KeystoreAPI = dcomm.NodeKeys()

  // test_name             response_promise                              resp_fn  matcher           expected_value/obtained_value
  const tests_spec: any = [
    [
      "createUserWeakPass",
      () => keystore.createUser(username1, "weak"),
      (x) => x,
      Matcher.toThrow,
      () => "password is too weak"
    ],
    [
      "createUser",
      () => keystore.createUser(username1, password),
      (x) => x,
      Matcher.toEqual,
      () => { return {} }
    ],
    [
      "createRepeatedUser",
      () => keystore.createUser(username1, password),
      (x) => x,
      Matcher.toThrow,
      () => "user already exists: " + username1
    ],
    [
      "listUsers",
      () => keystore.listUsers(),
      (x) => x,
      Matcher.toContain,
      () => [username1]
    ],
    [
      "exportUser",
      () => keystore.exportUser(username1, password),
      (x) => x,
      Matcher.toMatch,
      () => /\w{78}/
    ],
    [
      "getExportedUser",
      () => keystore.exportUser(username1, password),
      (x) => x,
      Matcher.Get,
      () => exportedUser
    ],
    [
      "importUser",
      () => keystore.importUser(username2, exportedUser.value, password),
      (x) => x,
      Matcher.toEqual,
      () => { return {} }
    ],
    [
      "exportImportUser",
      () =>
        (async () => {
          let exported = await keystore.exportUser(username1, password)
          return await keystore.importUser(username3, exported, password)
        })(),
      (x) => x,
      Matcher.toEqual,
      () => { return {} }
    ],
    [
      "listUsers2",
      () => keystore.listUsers(),
      (x) => x,
      Matcher.toContain,
      () => [username1, username2, username3]
    ],
    [
      "deleteUser1",
      () => keystore.deleteUser(username1, password),
      (x) => x,
      Matcher.toEqual,
      () => { return {} }
    ],
    [
      "deleteUser2",
      () => keystore.deleteUser(username2, password),
      (x) => x,
      Matcher.toEqual,
      () => { return {} }
    ],
    [
      "deleteUser3",
      () => keystore.deleteUser(username3, password),
      (x) => x,
      Matcher.toEqual,
      () => { return {} }
    ]
  ]

  createTests(tests_spec)
})