import { useEffect, useState } from 'react';
const MAX_PARALLEL = 3; // 资源导出最大并行

enum State {
  cancel = -1,
  pending = 0,
  done = 1
}

interface currentTs {
  id: number;
  state: State;
}

export function useExportQueue({
  assets,
  assetsKey = 'id',
  maxRarallel = MAX_PARALLEL
}: {
  assets: any[];
  assetsKey?: string;
  maxRarallel?: number;
}) {
  const [current, setCurrent] = useState<currentTs[]>([]);

  useEffect(() => {
    // 初始化
    if (assets.length) {
      !current.length &&
        setCurrent(
          assets
            .filter((d, i) => i < maxRarallel)
            .map((d) => {
              return {
                id: d[assetsKey],
                state: 0
              };
            })
        );
    }
  }, [assets]);

  const exportQueuelear = () => {
    setCurrent([]);
  };

  const watchBehavior = ({ id, state }) => {
    if (current.map((d) => d.id).includes(id)) {
      setCurrent((prev) => {
        const newCurrent: currentTs[] = prev.map((d) => {
          if (d.id === id) {
            return {
              id,
              state
            };
          }
          return d;
        });
        const firstItem = assets.filter((d) => !newCurrent.map((d) => d.id).includes(d[assetsKey])).shift();

        return newCurrent.concat(
          firstItem
            ? {
                id: firstItem[assetsKey],
                state: 0
              }
            : []
        );
      });
    }
  };

  return {
    current: current.filter((d) => !d.state).map((d) => d.id),
    watchBehavior,
    exportQueuelear
  };
}
