import iView from "iview";
import axios from "axios";

const calculatePercentage = (loaded, total) => Math.floor(loaded * 1.0) / total;

export function loadProgressBar(instance = axios) {
  let requestsCounter = 0;

  const setupStartProgress = () => {
    instance.interceptors.request.use(config => {
      requestsCounter++;
      iView.LoadingBar.start();
      return config;
    });
  };

  const setupUpdateProgress = () => {
    const update = e =>
      iView.LoadingBar.update(calculatePercentage(e.loaded, e.total));
    instance.defaults.onDownloadProgress = update;
    instance.defaults.onUploadProgress = update;
  };

  const setupStopProgress = () => {
    const responseFunc = response => {
      if (--requestsCounter === 0) {
        iView.LoadingBar.finish();
      }
      return response;
    };

    const errorFunc = error => {
      if (--requestsCounter === 0) {
        iView.LoadingBar.error();
      }
      console.log(error);
      throw error;
    };

    instance.interceptors.response.use(responseFunc, errorFunc);
  };

  setupStartProgress();
  setupUpdateProgress();
  setupStopProgress();
}
