import { onBeforeUnmount, ref } from 'vue';

/**
 * Execute code before next frame but async
 */
export function useLayoutState(defaultState) {
  var stateRef = ref(defaultState); // const [, forceUpdate] = useState({});

  var lastPromiseRef = ref(null);
  var updateBatchRef = ref([]);

  function setFrameState(updater) {
    updateBatchRef.value.push(updater);
    var promise = Promise.resolve();
    lastPromiseRef.value = promise;
    promise.then(function () {
      if (lastPromiseRef.value === promise) {
        var prevBatch = updateBatchRef.value; // const prevState = stateRef.value;

        updateBatchRef.value = [];
        prevBatch.forEach(function (batchUpdater) {
          stateRef.value = batchUpdater(stateRef.value);
        });
        lastPromiseRef.value = null;
      }
    });
  }

  onBeforeUnmount(function () {
    lastPromiseRef.value = null;
  });
  return [stateRef, setFrameState];
}
/** Lock frame, when frame pass reset the lock. */

export function useTimeoutLock(defaultState) {
  var frameRef = ref(defaultState || null);
  var timeoutRef = ref();

  function cleanUp() {
    window.clearTimeout(timeoutRef.value);
  }

  function setState(newState) {
    frameRef.value = newState;
    cleanUp();
    timeoutRef.value = window.setTimeout(function () {
      frameRef.value = null;
      timeoutRef.value = undefined;
    }, 100);
  }

  function getState() {
    return frameRef.value;
  }

  onBeforeUnmount(function () {
    cleanUp();
  });
  return [setState, getState];
}