import { useState, forwardRef, useImperativeHandle } from "react";
import {
  Checkbox,
  FormControlLabel,
} from '@material-ui/core';
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TaskRunner from "../../../utils/taskRunner";
import vehiclesAPI from "../../../services/vehiclesAPI";

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

  const [forcePush, setForcePush] = useState(false);

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

        const task = (vin, index) => {
          const progressMessage = `${index + 1}/${ids.length}`;
          return async () => vehiclesAPI.updateConfig(vin, forcePush, token)
            .then((response) => {
              if (response.error) {
                errorCount += 1;
                setMessage(`${progressMessage} ${response.error}: ${response.message}`);
              } else {
                setMessage(`${progressMessage} Updated config for ${vin}`);
              }
              return response;
            })
            .catch((error) => reject(error));
        }

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

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

  const handleChange = () => {
    setForcePush((forcePush) => !forcePush);
  }

  return (
    <div>
      <p>
        You are updating the config for the following VINs: {idCSV}.
      </p>
      <FormControlLabel
        label="Force Push"
        control={
          <Checkbox
            checked={forcePush}
            onChange={() => handleChange()}
          />
        }
      />
    </div>
  );
});