import React, { useContext, useState } from "react";

import api from "../../services/updatesAPI";
import { validateSoftwareVersion } from "../../utils/softwareVersions";
import { validateStatusMessage } from "../../utils/statusMessage";

export const SELECT_VERSION = "Select Version";
const FINAL_UPDATE_STATES = ["package_install_complete"];
const CarUpdatesContext = React.createContext();
const SELECT_VERSION_OBJ = { version: SELECT_VERSION }

const validateDeployClosure = (data, propertyName, errPfx) => {
  if (data === null) {
    throw new Error("No car update data");
  }

  if (!data.manifest_id || data.manifest_id === 0) {
    throw new Error("Manifest id required");
  }

  const { [propertyName]: value } = data;
  if (!value || value.length === 0) {
    throw new Error(`${errPfx} are required`);
  }
};

const validateDeployCarUpdates = (data) => {
  return validateDeployClosure(data, "vins", "Cars");
};

const validateDeployFleetUpdates = (data) => {
  return validateDeployClosure(data, "fleet_names", "Fleets");
};

export function downloadPercent(status) {
  if (!status) {
    return 0;
  }

  if (status.status === "install_succeeded") {
    return 100;
  }

  if (status.package_total === 0) {
    return 0;
  }

  return Math.floor((100 * status.package_current) / status.package_total);
}

export function installPercent(status) {
  if (!status) {
    return 0;
  }

  if (status.total_files === 0) {
    return 0;
  }

  return Math.floor((100 * status.installed) / status.total_files);
}

export const CarUpdatesProvider = ({ children }) => {
  const [busy, setBusy] = useState(false);
  const [carUpdates, setCarUpdates] = useState([]);
  const [versions, setVersions] = useState([SELECT_VERSION_OBJ]);
  const [totalVersions, setTotalVersions] = useState(0);
  const [versionRxSwins, setVersionRxSwins] = useState([]);
  const [totalVersionRxSwins, setTotalVersionRxSwins] = useState(0);
  const [totalCarUpdates, setTotalCarUpdates] = useState(0);
  const [delayCount, setDelayCount] = useState(0);
  let progressTimer = 0;

  const cancelUpdate = async (id, token) => {
    let result;

    try {
      setBusy(true);
      result = await api.cancelCarUpdate(id, token);
      if (result.error) {
        throw new Error(`Cancel car update error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const deployUpdate = async (id, token) => {
    let result;

    try {
      setBusy(true);
      result = await api.deployCarUpdate(id, token);
      if (result.error) {
        throw new Error(`Retry car update error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const deployCarUpdates = async (data, token) => {
    let result;

    try {
      setBusy(true);
      validateDeployCarUpdates(data);
      result = await api.createCarUpdates(data, token);
      if (result.error) {
        throw new Error(`Deploy car updates error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const deployFleetUpdates = async (data, token) => {
    let result;

    try {
      setBusy(true);
      validateDeployFleetUpdates(data);
      result = await api.createFleetUpdates(data, token);
      if (result.error) {
        throw new Error(`Deploy fleet updates error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const getCarUpdates = async (search, token) => {
    let result;

    try {
      setBusy(true);
      result = await api.getCarUpdates(search, token);
      if (result.error)
        throw new Error(`Get car updates error. ${result.message}`);
      result.data.forEach((item) => {
        item.progress = 0;
        item.msg = item.status;
        applyProgressStatus(item, item);
      });
      setCarUpdates(result.data);
      if (search && search.offset === 0 && result.total) {
        setTotalCarUpdates(result.total);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const getVINUpdates = async (vin, token) => {
    let result;

    try {
      setBusy(true);
      result = await api.getVINUpdates(vin, token);
      if (result.error) {
        throw new Error(`Get VIN updates error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const applyProgressStatus = (item, status) => {
    if (validateStatusMessage(status)) {
      if (status.msg === "downloading") {
        item.progress = downloadPercent(status);
        item.status = `${item.ecu || ""} downloading ${item.progress}%`.trim();
        return;
      } else if (status.msg === "package_download_complete") {
        item.progress = 100;
        item.status = "download complete";
        return;
      } else if (status.msg === "installing") {
        item.progress = installPercent(status);
        item.status = `${item.ecu || ""} installing ${item.progress}%`.trim();
        return;
      } else if (status.msg === "package_install_complete") {
        item.progress = 100;
        item.status = "install complete";
        return;
      }
    }
    delete item.progress;

    if (status.msg === "cleanup_succeeded") {
      return;
    }

    item.status = status.msg;
  };

  const applyProgressStatuses = (statuses) => {
    let items = JSON.parse(JSON.stringify(carUpdates));

    statuses.forEach((status) => {
      let x = items.find((item) => status.car_update_id === item.id);
      if (!x || status.car_update_id === 0) return;
      applyProgressStatus(x, status);
    });

    setCarUpdates(items);
  };

  const updateStatusProgress = async (token) => {
    stopMonitor();

    if (!token || carUpdates.length === 0) return;

    try {
      setBusy(true);
      const carupdateids = carUpdates.reduce((accum, update) => {
        if (update.status !== "installed") accum.push(update.id);
        return accum;
      }, []);
      if (carupdateids.length === 0) return;

      const result = await api.getCarUpdateProgress(
        carupdateids.join(","),
        token
      );
      if (result.error) {
        throw new Error(`Get update progress error. ${result.message}`);
      }

      applyProgressStatuses(result.statuses);
    } catch (e) {
      throw new Error(`Get update progress error. ${e}`);
    } finally {
      setBusy(false);
    }
  };

  const getDelay = () => {
    if (delayCount < 3) {
      setDelayCount(delayCount + 1);
      return 1000;
    }
    for (let i = 0, len = carUpdates.length; i < len; i++) {
      if (FINAL_UPDATE_STATES.indexOf(carUpdates[i].status) === -1) return 1000;
    }
    return 10000;
  };

  const startMonitor = async (token) => {
    const delay = getDelay();
    stopMonitor();
    progressTimer = setTimeout(() => {
      updateStatusProgress(token);
    }, delay);
  };

  const stopMonitor = async () => {
    if (progressTimer === 0) return;
    clearTimeout(progressTimer);
    progressTimer = 0;
  };

  const getLog = async (query, token) => {
    let result;

    try {
      setBusy(true);
      result = await api.getCarUpdateLog(query, token);
      if (result.error) {
        throw new Error(`Get car update log error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const getSUMSVersions = async (token) => {
    let result;

    try {
      setBusy(true);

      result = await api.getSUMSVersions(null, token);
      if (result.error) {
        throw new Error(`Get software versions error. ${result.message}`);
      }

      result.data.unshift(SELECT_VERSION_OBJ)
      setVersions(result.data);
    } finally {
      setBusy(false);
    }

    return result;
  };

  const getSUMSVersionsList = async (options, token) => {
    let result;

    try {
      setBusy(true);

      result = await api.getSUMSVersions(options, token);
      if (result.error) {
        throw new Error(`Get software versions error. ${result.message}`);
      }

      setVersions(result.data);
      if (options && options.offset === 0 && result.total) {
        setTotalVersions(result.total);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const addSUMSVersion = async (sums_version, os_version, token) => {
    let result;

    try {
      setBusy(true);

      if (!validateSoftwareVersion(sums_version)) throw new Error(`invalid version ${sums_version}`);

      const data = {
        "sumsversions": [
          {
            "version": sums_version,
            "os_version": os_version,
          }
        ],
      }

      result = await api.addSUMSVersion(data, token);
      if (result.error) {
        throw new Error(`Add SUMS version error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  }

  const deleteSUMSVersion = async (version, token) => {
    let result;

    try {
      setBusy(true);

      result = await api.deleteSUMSVersion(version, token);
      if (result.error) {
        throw new Error(`Delete software version error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  }

  const updateSUMSVersion = async (id, version, token) => {
    let result;

    try {
      setBusy(true);

      if (!validateSoftwareVersion(version)) throw new Error(`invalid version ${version}`);

      result = await api.updateSUMSVersion(id, version, token);
      if (result.error) {
        throw new Error(`Update manifest version error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const getSUMSVersionRxSwins = async (sums_version, options, token) => {
    let result;

    try {
      setBusy(true);

      result = await api.getSUMSVersionRxSwins(sums_version, options, token);
      if (result.error)
        throw new Error(`Get software version rxswins error. ${result.message}`);

      setVersionRxSwins(result.data);
      if (options && options.offset === 0 && result.total) {
        setTotalVersionRxSwins(result.total);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const deleteSUMSVersionRxSwins = async (sums_version, rxswin, token) => {
    let result;

    try {
      setBusy(true);

      result = await api.deleteSUMSVersionRxSwins(sums_version, rxswin, token);
      if (result.error) {
        throw new Error(`Delete software version rxswin error. ${result.message}`);
      }
    } finally {
      setBusy(false);
    }

    return result;
  };

  const addSUMSVersionRxSwins = async (sums_version, data, token) => {
    try {
      setBusy(true);
      const result = await api.addSUMSVersionRxSwins(sums_version, data, token);
      if (result.error) {
        throw new Error(`Add software version rxswin error. ${result.message}`);
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  return (
    <CarUpdatesContext.Provider
      value={{
        busy,
        carUpdates,
        totalCarUpdates,
        versionRxSwins,
        versions,
        totalVersions,
        cancelUpdate,
        deployUpdate,
        deployCarUpdates,
        deployFleetUpdates,
        getCarUpdates,
        getLog,
        getSUMSVersions,
        getSUMSVersionsList,
        addSUMSVersion,
        deleteSUMSVersion,
        getVINUpdates,
        startMonitor,
        stopMonitor,
        updateSUMSVersion,
        getSUMSVersionRxSwins,
        totalVersionRxSwins,
        deleteSUMSVersionRxSwins,
        addSUMSVersionRxSwins,
      }}
    >
      {children}
    </CarUpdatesContext.Provider>
  );
};

export const useCarUpdatesContext = () => useContext(CarUpdatesContext);