import { invariant } from "../../invariant";

export default function create() {
  let lock = null;

  function isClaimed() {
    return Boolean(lock);
  }

  function isActive(value) {
    return value === lock;
  }

  function claim(abandon) {
    invariant(!lock, "Cannot claim lock as it is already claimed");
    const newLock = {
      abandon
    };
    // update singleton
    lock = newLock;
    // return lock
    return newLock;
  }

  function release() {
    invariant(lock, "Cannot release lock when there is no lock");
    lock = null;
  }

  function tryAbandon() {
    if (lock) {
      lock.abandon();
      release();
    }
  }

  return {
    isClaimed,
    isActive,
    claim,
    release,
    tryAbandon
  };
}
