import { useState } from "react";
import manifestsAPI from "../services/manifestsAPI";
import TaskRunner from "../utils/taskRunner";

export const useUpdateManifest = (token) => {
  const [updateManifestIds, setUpdateManifestIds] = useState([]);
  const [makeActive, setMakeActive] = useState(false);

  const remove = async () => {
    return new Promise((resolve) => {
      const taskRunner = new TaskRunner(30, updateManifestIds.length);
      let errorCount = 0;

      const task = (id) => {
        return async () => manifestsAPI.deleteManifest(id, token);
      }

      updateManifestIds.forEach((id) => taskRunner.push(task(id))
        .then((response) => {
          if (response.error) {
            errorCount += 1;
          }
        })
      );
      taskRunner.onComplete().then((responses) => resolve({
        summary: `${updateManifestIds.length - errorCount} out of ${updateManifestIds.length} manifests were deleted.`,
        responses,
      }));
    });
  }

  const archive = async () => {
    return manifestsAPI.archiveManifest({
      ids: updateManifestIds,
      active: makeActive,
    }, token);
  }

  return {
    updateManifestIds,
    setUpdateManifestIds,
    makeActive,
    setMakeActive,
    archive,
    remove,
  };
};
