export function createRenderTargetPool(factory) {
  const targets = new Map();

  return {
    get(key, width, height, options) {
      if (!targets.has(key)) {
        targets.set(key, factory(width, height, options));
      }
      return targets.get(key);
    },
    invalidateSize(width, height) {
      for (const [key, target] of targets) {
        if (target.width !== width || target.height !== height) {
          target.dispose();
          targets.delete(key);
        }
      }
    },
    release(key) {
      const target = targets.get(key);
      if (!target) return false;
      target.dispose();
      targets.delete(key);
      return true;
    },
    retain(keys) {
      const retained = new Set(keys);
      for (const key of [...targets.keys()]) {
        if (!retained.has(key)) this.release(key);
      }
    },
    dispose() {
      for (const key of [...targets.keys()]) this.release(key);
    },
    size() {
      return targets.size;
    },
  };
}

export function ensureRenderTarget(target, width, height, factory, options) {
  if (target && target.width === width && target.height === height) return target;
  if (target) target.dispose();
  return factory(width, height, options);
}

export function ensureRenderTargetPair(pair, width, height, factory, options) {
  const [first, second] = pair || [];
  if (
    first && second
    && first.width === width && first.height === height
    && second.width === width && second.height === height
  ) {
    return pair;
  }
  if (first) first.dispose();
  if (second) second.dispose();
  return [factory(width, height, options), factory(width, height, options)];
}
