import test from "ava";
import { Mutex } from "../../client/helpers.js";
import crypto from "crypto";

const rand = (min, max) => crypto.randomInt(min, max);

const lock = new Mutex();


test("quick helpers test", async (t) => {
  const wait_count = rand(0, 50);

  await lock.hold();

  setTimeout(() => {
    lock.release();
  }, rand(100, 300));

  const tests = [];

  for(let i = 0; i < wait_count; i++) {
    let t = (async () => {
      await lock.hold();
      setTimeout(() => {
        console.debug(`lock ${i} releasing, queue length: ${lock.count}`);
        lock.release();
      }, rand(0, 100));

      return true;
    })();

    tests.push(t);
  }

  let interval = setInterval(async () => {
    // grabbing another lock
    const test = await lock.attempt();

    if(test === true) {
      lock.release();
      clearInterval(interval);
    }
  }, rand(0, 300));


  const all = await Promise.all(tests);
  t.is(all.length, wait_count);
})
