import axiosWrapper from '../services/axiosWrapper';

export const DSR_LEVEL_MEASUREMENT_UNIT = 'dsr_level_unit';
export const ESTIMATE_LEVEL_MEASUREMENT_UNIT = 'estimate_level_unit';
export const PORTAL_LEVEL_UNIT_SYMBOL = 'portal_level_unit_symbol';
export const ESTIMATE_LEVEL_UNIT_SYMBOL = 'estimate_level_unit_symbol';
export const SYSTEM_GENERATED_UNIT = 'SYSTEM GENERATED';
export const takeoffsStatusList = ['LIST', 'CREATE', 'DETAILS', ''];

export const measurementSources = {
  MEASUREMENTS: 'measurements',
  TAKEOFFS: 'takeoffs',
  ESTIMATE: 'estimate',
  TAKEOFF_SIDEBAR: 'takeoff_sidebar',
};

export const numberingSystemOptions = [
  {
    item: '1, 2, 3',
    value: 0,
  },
  {
    item: 'a, b, c',
    value: 1,
  },
  {
    item: 'A, B, C',
    value: 2,
  },
  {
    item: 'i, ii, iii',
    value: 3,
  },
  {
    item: 'I, II, III',
    value: 4,
  },
];

export const takeoffSources = { VIEWER: 'viewer', ESTIMATE: 'estimate' };

export const itemListSources = { COST_DATABASE: 'costDatabase', ESTIMATE: 'estimate', ADD_ITEM_POPUP: 'addItemToBoq' };

export const unitTypesList = [
  { title: 'LINEAR', value: 'linear', name: 'Linear' },
  { title: 'AREA', value: 'area', name: 'Area' },
  { title: 'VOLUME', value: 'volume', name: 'Volume' },
  { title: 'COUNT', value: 'count', name: 'Count' },
];

export const unitTypes = {
  LINEAR: { value: 'Linear', name: 'Length' },
  AREA: { value: 'Area', name: 'Area' },
  VOLUME: { value: 'Volume', name: 'Volume' },
  COUNT: { value: 'Count', name: 'Count' },
};

export const twoDOperators = [
  { id: 'c1', title: unitTypes.COUNT.value, text: 'Count object by clicking on the plan to place a symbol' },
  { id: 'l1', title: unitTypes.LINEAR.value, text: 'Measure a distance by clicking on each point' },
  { id: 'a1', title: unitTypes.AREA.value, text: 'Measure a flat area by clicking on each corner' },
  { id: 'v1', title: unitTypes.VOLUME.value, text: 'Enter the depth and measure volume by clicking on each corner' },
];

export const threeDOperators = [
  { id: 'o1', title: 'objects', text: 'Measure object parameter by clicking on the object' },
  { id: 's1', title: 'surface', text: 'Measure distance/area by clicking on the surface' },
  { id: 'e1', title: 'edge', text: 'Measure distance by clicking on the edges' },
  { id: 'p1', title: 'point', text: 'Count points by clicking on the surface to place a symbol' },
];

export const getMeasurementDetails = (_name) => {
  let result = { type: null, name: null, units: null };

  switch (_name) {
    case 'QTakeOffLengthMarkup':
    case 'QTakeOffLengthWithBreakMarkup':
    case 'QTakeOffCircumferenceMarkup':
    case 'LinearDropMarkup':
    case 'SlopeLengthMarkup':
    case 'QTakeOffThreePtArcLengthMarkup':
      result = { type: unitTypes.LINEAR.value, name: unitTypes.LINEAR.name };
      break;

    case 'QTakeOffAreaMarkup':
    case 'SlopeAreaMarkup':
    case 'SurfaceAreaDeductionMarkup':
    case 'SurfaceAreaDeductionDepthMarkup':
    case 'QTakeOffCircleAreaMarkup':
    case 'Surface Area':
    case 'QTakeOffThreePtArcAreaMarkup':
      result = { type: unitTypes.AREA.value, name: unitTypes.AREA.name };
      break;

    case 'TwoDVolumeMarkup':
    case 'OneDVolumeMarkup':
      result = { type: unitTypes.VOLUME.value, name: unitTypes.VOLUME.name };
      break;

    case 'QTakeOffCountMarkup':
      result = { type: unitTypes.COUNT.value, name: unitTypes.COUNT.name };

    default:
      break;
  }
  return result;
};

export const countSymbols = [
  { name: 'TRIANGLE', value: 0 },
  { name: 'SQUARE', value: 1 },
  { name: 'PENTAGON', value: 2 },
  { name: 'HEXAGON', value: 3 },
  { name: 'OCTAGON', value: 4 },
];

export const hexToRgb = (h) => {
  let r = 0;
  let g = 0;
  let b = 0;

  if (h.length === 4 || h.length === 5) {
    r = `0x${h[1]}${h[1]}`;
    g = `0x${h[2]}${h[2]}`;
    b = `0x${h[3]}${h[3]}`;
  }

  if (h.length === 7 || h.length === 9) {
    r = `0x${h[1]}${h[2]}`;
    g = `0x${h[3]}${h[4]}`;
    b = `0x${h[5]}${h[6]}`;
  }

  return { red: parseInt(r), green: parseInt(g), blue: parseInt(b) };
};

export const getValueInStandardUnits = ({ units, quantity }) => {
  if (!units) return quantity;
  let factor = 1;
  switch (units) {
    case 'mm':
      factor = 1000;
      break;

    case 'sqmm':
      factor = 1000000;
      break;

    case 'cumm':
      factor = 1000000000;
      break;

    default:
      break;
  }

  if (factor === 1) return quantity;
  return (parseFloat(quantity) / factor).toFixed(2);
};

export const getValueInLowestUnits = ({ type, quantity }) => {
  if (!quantity) return quantity;
  let factor = 1;
  switch (type) {
    case 'linear':
      factor = 1000;
      break;

    case 'area':
      factor = 1000000;
      break;

    case 'volume':
      factor = 1000000000;
      break;

    default:
      break;
  }

  if (factor === 1) return quantity;
  return parseFloat(quantity) * factor;
};

export const getStandardUnits = ({ units }) => {
  if (!units) return;
  switch (units) {
    case 'mm':
      return 'm';
    case 'sqmm':
      return 'sqm';
    case 'cumm':
      return 'cum';
    default:
      return units;
  }
};

export const getDisplayQuantity = ({ quantity, factor, rate }) => {
  const output = {};
  output.quantity = factor && quantity ? parseFloat(parseFloat(quantity / factor).toFixed(2)) : quantity;
  output.amount = quantity && rate && parseFloat(parseFloat(output.quantity * rate).toFixed(2));

  return output;
};

export const getDefaultQuantity = ({ quantity, factor }) => {
  if (factor && quantity) {
    return parseFloat(quantity * factor);
  }

  return quantity;
};

export const correctDecimalPlaces = ({ value, decimals }) => {
  if (!value) return value;
  if (typeof decimals !== 'number') decimals = 2;

  return parseFloat(parseFloat(value).toFixed(decimals));
};

export const loadMarkupStylesViewer = ({
  viewerImpl, viewerMarkup, lineThickness, lineColor, fillColor, fillOpacity, symbolSize, countSymbol,
}) => {
  if (!viewerMarkup) return;

  if (viewerMarkup.setStrokeWidth && (typeof lineThickness === 'string' || typeof lineThickness === 'number')) viewerMarkup.setStrokeWidth(lineThickness);
  if (viewerMarkup.setStrokeColor && lineColor) viewerMarkup.setStrokeColor(lineColor);
  if (viewerMarkup.setFillColor && fillColor) viewerMarkup.setFillColor(fillColor);
  if (viewerMarkup.setFillOpacity && (typeof fillOpacity === 'string' || typeof fillOpacity === 'number')) viewerMarkup.setFillOpacity(fillOpacity);
  if (viewerMarkup.setMarkupSize && (typeof symbolSize === 'string' || typeof symbolSize === 'number')) viewerMarkup.setMarkupSize(symbolSize);
  if (viewerMarkup.setMarkupShape && typeof countSymbol === 'number') viewerMarkup.setMarkupShape(countSymbol);

  if (viewerImpl) viewerImpl.hwv.markupManager.refreshMarkup();
};

export const prepareMarkupColor = (color) => {
  const rgbColor = hexToRgb(color);
  return new Communicator.Color(rgbColor.red, rgbColor.green, rgbColor.blue);
};

export const prepareTakeoffColors = ({ takeoffLineColor, takeoffFillColor }) => {
  const lineColorRGB = takeoffLineColor ? hexToRgb(takeoffLineColor) : null;
  const lineColor = lineColorRGB ? new Communicator.Color(lineColorRGB.red, lineColorRGB.green, lineColorRGB.blue) : null;
  const fillColorRGB = takeoffFillColor ? hexToRgb(takeoffFillColor) : null;
  const fillColor = fillColorRGB ? new Communicator.Color(fillColorRGB.red, fillColorRGB.green, fillColorRGB.blue) : null;
  return { lineColor, fillColor };
};

export const setMeasurementsData = (data) => ({ type: 'SET_MEASUREMENTS_DATA', data });

export const setTakeoffsListAction = (data) => ({ type: 'SET_TAKEOFFS_LIST', data });

export const setTakeoff = (data) => ({ type: 'SET_TAKEOFF', data });

export const setAdditionalCost = (data) => ({ type: 'SET_ADDITIONAL_COST', data });

export const setTakeoffsModalStatusAction = (data) => ({ type: 'SET_TAKEOFFS_MODAL_STATUS', data });

export const setMeasurementsModalStatusAction = (data) => ({ type: 'SET_MEASUREMENTS_MODAL_STATUS', data });

export const setIsMeasurementStarted = (data) => ({ type: 'SET_IS_MEASUREMENT_STARTED', data });

export const setCostdatabase = (data) => ({ type: 'SET_COST_DATABASE', data });

export const changeEstimateUnits = async (data) => {
  console.log(data);
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/changeDisplayUnit`, data);
  return response;
};

export const canUpdateMeasurementUnitType = async ({ id }) => {
  const data = { id };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/units/canUpdateMeasurementUnitType`, data);
  return response;
};

export const createNewEstimate = async ({
  name, description, costIndex, spaceId, projectId,
}) => {
  const data = {
    action: 'insert',
    value: {
      name,
      description,
      costIndex,
      spaceId,
      projectId,
    },
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/getEstimateList`, data);
  return response;
};

export const saveItemMeasurementUnit = async ({
  itemId, measurementUnitId, conversionRatePU, conversionRateMU, resourceLevel, resourceId,
}) => {
  const data = {
    itemId,
    measurementUnitId,
    conversionRate: conversionRatePU.concat(':', conversionRateMU),
    resourceLevel,
    resourceId,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/units/saveItemMeasurementUnit`, data);
  return response;
};

export const getItemMeasurementUnit = async ({
  resourceLevel, resourceId, itemId, estimateVersionId, dsrVersionId,
}) => {
  const data = {
    resourceLevel,
    resourceId,
    itemId,
    estimateVersionId,
    dsrVersionId,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/units/getItemMeasurementUnit`, data);
  return response;
};

export const syncItemMeasurementUnit = async ({
  itemId, resourceLevel, resourceId, dsrVersionId,
}) => {
  const data = {
    itemId,
    resourceLevel,
    resourceId,
    dsrVersionId,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/units/syncItemMeasurementUnit`, data);
  return response;
};

export const deleteItemsFromTakeoffs = async ({ data, estimateId }) => {
  const payload = { data, estimateId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/removeItemsFromTakeoffs`, payload);
  return response;
};

export const addFilesToEstimate = async ({ dataArr }) => {
  const data = { data: dataArr };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/addFilesToEstimate`, data);
  return response;
};

export const getTakeoffsList = async ({ estimateId, excludeMeasurements = null, versionId }) => {
  const data = { value: { params: { estimateId, excludeMeasurements, versionId } } };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/getTakeoffsList`, data);
  return response;
};

export function getTakeoffsListData({ estimateId, excludeMeasurements = null, versionId }) {
  return async (dispatch) => {
    const data = { value: { params: { estimateId, excludeMeasurements, versionId } } };
    const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/getTakeoffsList`, data);
    if (!response.data.status) return;
    dispatch(setTakeoffsListAction(response.data.result));
    return response.data.result;
  };
}

export function setTakeoffsList() {
  return (dispatch) => dispatch(setTakeoffsListAction([]));
}

export const getTakeoff = async ({ id, versionId, estimateId }) => {
  const data = { id, versionId, estimateId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/getTakeoff`, data);
  return response;
};

export function getTakeoffData({ id, versionId, estimateId }) {
  return async (dispatch) => {
    const data = { id, versionId, estimateId };
    const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/getTakeoff`, data);
    if (!response.data.status) return;

    const takeoffData = response.data.result;
    const saveData = {
      ...takeoffData,
      quantity: getDisplayQuantity({ quantity: takeoffData.quantity, factor: takeoffData.factor }).quantity,
      additionalQuantity: getDisplayQuantity({ quantity: takeoffData.additionalQuantity, factor: takeoffData.factor }).quantity,
    };

    dispatch(setTakeoff(saveData));
    return saveData;
  };
}

export function setTakeoffData(data) {
  return (dispatch) => dispatch(setTakeoff(data));
}

export const createTakeoff = async ({
  name, description, type, estimateId,
}) => {
  const data = {
    name,
    description,
    type,
    estimateId,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/createTakeoff`, data);
  return response;
};
export const getBoqData = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/getBoqData`, data);
  return response;
};
export const getEstimateItems = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/getEstimateItems`, data);
  return response;
};

export const updateTakeoff = async ({
  id, name, description, type, additionalQuantity, estimateId, units, factor, lineColor, lineThickness, fillColor, fillOpacity, symbolSize, countSymbol,
}) => {
  additionalQuantity = getDefaultQuantity({ factor, quantity: parseFloat(additionalQuantity) });
  const data = {
    action: 'update',
    value: {
      id,
      name,
      description,
      additionalQuantity,
      unitsId: units,
      lineColor,
      lineThickness: parseFloat(lineThickness),
      fillColor,
      fillOpacity: parseFloat(fillOpacity),
      symbolSize: parseFloat(symbolSize),
      countSymbol: parseFloat(countSymbol),
    },
    params: { estimateId },
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/getTakeoffsList`, data);
  return response;
};

export const deleteTakeoff = async ({ id, estimateId }) => {
  const data = { action: 'remove', key: id, params: { estimateId } };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/getTakeoffsList`, data);
  return response;
};

export const duplicateTakeoff = async ({
  id, name, description, type, linkMeasurements, linkItems,
}) => {
  const data = {
    id,
    name,
    description,
    type,
    linkMeasurements,
    linkItems,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/duplicateTakeoff`, data);
  return response;
};

export const duplicateItemInTakeoff = async ({ itemId, takeoffId, estimateId }) => {
  const data = { itemId, takeoffId, estimateId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/duplicateItemInTakeoff`, data);
  return response;
};

export const checkStatusValidity = (data) => !!takeoffsStatusList.includes(data);

export function setTakeoffsModalStatus({ status }) {
  if (!checkStatusValidity(status)) return;
  return async (dispatch) => dispatch(setTakeoffsModalStatusAction({ status }));
}

export const addItemsToTakeoffs = async (data, shouldReturnResult = true) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/takeoffs/addItemsToTakeoffs`, data);
  if (shouldReturnResult) return response;
};

export const addMeasurementsToTakeoffs = async (data, shouldReturnResult = true) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/measurements/addMeasurementsToTakeoffs`, data);
  if (shouldReturnResult) return response;
};

export function setMeasurementsModalStatus({ status }) {
  if (status !== true && status !== false) return;
  return async (dispatch) => dispatch(setMeasurementsModalStatusAction({ status }));
}

export const createMeasurement = async ({
  id, name, type, quantity, units, takeoffId, scale, markup, fileVersionId, estimateId, elements, nestedMeasurements,
}) => {
  const data = {
    id,
    name,
    type,
    quantity,
    units,
    takeoffId,
    scale,
    markup,
    fileVersionId,
    estimateId,
    elements,
    nestedMeasurements,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/measurements/createMeasurement`, data);
  return response;
};

export const updateMeasurement = async (params) => {
  const data = {
    action: 'update',
    value: params,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/measurements/getMeasurements`, data);
  return response;
};

export const updateMeasurementTags = async ({ id, tags, estimateId }) => {
  const data = { id, tags, estimateId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/measurements/updateMeasurementTags`, data);
  return response;
};

export function getMeasurements({
  estimateId, takeoffId, fileVersionId, versionId,
}) {
  return async (dispatch) => {
    const data = {
      value: {
        params: {
          estimateId,
          takeoffId,
          fileVersionId,
          versionId,
        },
      },
    };
    const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/measurements/getMeasurements`, data);
    if (response.data.status) dispatch(setMeasurementsData(response.data.result));
  };
}

export const deleteMeasurement = async ({ key, action, estimateId }) => {
  const data = { key, action, params: { estimateId } };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/measurements/getMeasurements`, data);
  return response;
};

export function getAdditionalCost({ estimateId, versionId }) {
  return async (dispatch) => {
    const data = { estimateId, versionId };
    const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/getAdditionalCost`, data);
    if (response.data.status) dispatch(setAdditionalCost(response.data.data));
  };
}

export const saveAdditionalCost = async ({ estimateId, name, value }) => {
  const data = { estimateId, name, value };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/saveAdditionalCost`, data);
  return response;
};

export const createQuery = async ({ fileVersionId, estimateId }) => {
  const data = { value: { fileVersionId, estimateId }, action: 'insert' };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/queries/queriesData`, data);
  return response;
};

export const getQueryData = async ({ fileVersionId, id }) => {
  const data = { value: { params: { fileVersionId, id } } };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/queries/queriesData`, data);
  return response;
};

export const updateQuery = async ({ id, name, queryRule }) => {
  const value = { id };
  if (name) value.name = name;
  if (queryRule) value.queryRule = queryRule;

  const data = { action: 'update', value };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/queries/queriesData`, data);
  return response;
};

export const deleteQueries = async ({ ids }) => {
  const data = { action: 'remove', value: { ids } };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/queries/queriesData`, data);
  return response;
};

export const saveItemVariableRate = async ({
  itemId, isVariableRateEnabled, rangeUnit, itemVariableRateRulesList,
}) => {
  const data = {
    itemId,
    isVariableRateEnabled,
    rangeUnit,
    itemVariableRateRulesList,
  };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/saveItemVariableRate`, data);
  return response;
};

export const getItemVariableRateData = async ({ itemId, dsrVersionId }) => {
  const data = { itemId, dsrVersionId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/getItemVariableRateData`, data);
  return response;
};

export const saveItemRangeUnitValue = async ({ itemId, estimateId, rangeUnitValue }) => {
  const data = { itemId, estimateId, rangeUnitValue };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/saveEstimateItem`, data);
  return response;
};

export const saveEstimateStatus = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/saveEstimateStatus`, data);
  return response;
};

export const saveItemCostIndexValue = async ({ itemId, estimateId, costIndex }) => {
  const data = { itemId, estimateId, costIndex };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/saveEstimateItem`, data);
  return response;
};

export const getEstimateVersionInfo = async ({ estimateId }) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/getEstimateVersion`, { estimateId });
  return response;
};

export const createEstimateVersion = async ({ estimateId }) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/createEstimateVersion`, { estimateId });
  return response;
};

export const restoreEstimateVersion = async ({ estimateId, restoreEstimateVersionId }) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/restoreEstimateVersion`, { estimateId, restoreEstimateVersionId });
  return response;
};

export const saveEstimateItemsFromExcelSheet = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/saveEstimateItemsFromExcelSheet`, data);
  return response;
};

export const changeDsrVersionAttachedToEstimate = async ({ id, upgradeDsrVersion = true }) => {
  const data = { action: 'update', value: { id, upgradeDsrVersion }, key: id };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/getEstimateList`, data);
  return response;
};

export const getAllVersionsOfDsr = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/getAllVersionsOfDsr`, data);
  return response;
};

export const getSymbolsForUnit = async ({ unitId }) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/units/getSymbolsForUnit`, { unitId });
  return response;
};

export const getCostDatabase = ({ id, dsrVersionId }) => async (dispatch) => {
  const data = { value: { id, dsrVersionId } };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/getDsrData`, data);
  if (response.data.status) {
    dispatch(setCostdatabase(response.data.result[0]));
  }
};

export const clearCostDatabaseRedux = () => (dispatch) => {
  dispatch(setCostdatabase({}));
};

export const publishCostDatabaseVersion = async ({ dsrId }) => {
  const data = { dsrId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/publishCostDatabaseVersion`, data);
  return response;
};

export const discardCostDatabaseDraftVersion = async ({ dsrId }) => {
  const data = { dsrId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/discardDraftVersion`, data);
  return response;
};

export const getEstimateTotal = async ({ estimateId, versionId }) => {
  const data = { estimateId, versionId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/getEstimateTotal`, data);
  return response;
};

export const getEstimateItemNumberingSystem = async ({ estimateId, versionId }) => {
  const data = { estimateId, versionId };
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/getEstimateItemNumberingSystem`, data);
  return response;
};

export const saveEstimateItemNumberingSystem = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/dsr/saveEstimateItemNumberingSystem`, data);
  return response;
};

export const updatedEstimateItemSerial = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/updatedEstimateItemSerial`, data);
  return response;
};

export const nestEstimateItem = async (data) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/nestLatest0Child`, data);
  return response;
};

export const getPurchaseUnits = async () => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/units/getPurchaseUnits`);
  return response;
};

export const checkIfDsrVersionIsLatest = async ({ estimateId }) => {
  const response = await axiosWrapper.post(`${process.env.REACT_APP_CUBE_BACKEND}/estimate/checkIfDsrVersionIsLatest`, { estimateId });
  return response;
};
