import { forwardRef, useImperativeHandle } from "react";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TaskRunner from "../../../utils/taskRunner";
import updatesAPI from "../../../services/updatesAPI";

export default forwardRef(({
  ids,
  idCSV,
}, ref) => {
  const { setMessage } = useStatusContext();
  const { token: { idToken: { jwtToken: token } } } = useUserContext();

  useImperativeHandle(ref, () => ({
    async submit() {
      return new Promise((resolve, reject) => {
        const taskRunner = new TaskRunner(30, ids.length);
        let errorCount = 0;

        const task = (id, index) => {
          const progressMessage = `${index + 1}/${ids.length}`;
          return async () => updatesAPI.deployCarUpdate(id, token)
            .then((response) => {
              if (response.error) {
                errorCount += 1;
                setMessage(`${progressMessage} ${response.error}: ${response.message}`);
              } else {
                setMessage(`${progressMessage} Redeployed update ${id}`);
              }
              return response;
            })
            .catch((error) => reject(error));
        }

        ids.forEach((id, i) => {
          taskRunner.push(task(id, i));
        });

        taskRunner.onComplete().then((responses) => {
          const completeMessage = `${ids.length - errorCount}/${ids.length}`;
          setMessage(`Successfully rededployed ${completeMessage} updates.`);
          resolve(responses);
        });
      });
    },
  }));

  return (
    <div>
      <p>
        You are redeploying the following updates: {idCSV}.
      </p>
    </div>
  );
});