import axios from 'axios';
import { IAccount } from 'core/services/CrmService/types/entities';
import ELTService from 'core/services/ELTService';
import { ICalculationStore } from 'core/types/Calculation/Store';
import { toJS } from 'mobx';
import { map_evo_id_elt_FieldName } from '../lib/resetIns';

const CancelToken = axios.CancelToken;
export let sources = {};

export function cancelRequests(insType: string) {
  if (sources[insType]) sources[insType].cancel();
}

export const fetchData = (insType: string, composeRequest, convertEltResult) =>
  function (this: ICalculationStore) {
    sources[insType] = CancelToken.source();

    const { ELTStore } = this.stores;

    const evo_id_elt_fieldName = map_evo_id_elt_FieldName[insType](this);

    const requests = ELTStore[insType].list.map(
      (company: IAccount & { isFetching: boolean }, i: number) => {
        company.isFetching = true;
        return new Promise<void>((resolve, reject) => {
          const request = composeRequest.call(this, company);
          ELTService[insType]
            .getCalculation(
              {
                companyIds: [company[evo_id_elt_fieldName]],
                ...request,
              },
              sources[insType].token,
            )
            .then(res => {
              if (
                !company[evo_id_elt_fieldName] ||
                !res[company[evo_id_elt_fieldName]]
              ) {
                return;
              }
              const converted = convertEltResult(
                res[company[evo_id_elt_fieldName]],
                company.accountid,
                toJS(this.getValues(['leasingPeriod'])),
              );
              ELTStore.setCompanyRes(
                insType,
                i,
                Object.assign(company, converted),
              );
            })
            .catch(err => {
              reject(err);
            })
            .finally(() => {
              company.isFetching = false;
              resolve();
            });
        });
      },
    );

    return Promise.race(requests);
  };
