import axiosApi from "@assets/js/axios-api";

export function addToBuyLater (action, element) {
  sendAjaxFromForm({
    action: action,
    method: 'GET',
  })
    .then(json => {
      if (json['success']) {
        updateBuyLaterList(element);
      }
    })
    .catch(err => console.log(err, err.response));
}

export function updateBuyLaterList(listBuyLater){
  const position = (listBuyLater) ? listBuyLater.dataset.position : '';
  const action = 'index.php?route=module/buy_later/reloadBuyLaterList&cart=true&position=' + position,
    method= 'GET';

  const requestConfig = {
    url: `${action}&ajax=1`,
    method,
  };

  axiosApi(requestConfig).then(({data}) => {

    let contextData = sendAjaxFromForm({
      action: `${window.location.href}&ajax=1`,
      method: 'GET',
    }).then( function (){
      if (data.moduleBuyLater && listBuyLater) {
        listBuyLater.innerHTML = data.moduleBuyLater.html;
        listBuyLater.dataset.productsCount = data.moduleBuyLater.productsCount;
      } else {
        return window.location.reload();
      }
      gridFix();
      $(".load-image").imageLoad();
      initActionProductBox(listBuyLater);
    });
  });
}

function sendAjaxFromForm(form, cancelToken = null) {
  const { action, method } = form;
  const requestConfig = {
    url: `${action}&ajax=1`,
    method,
  };

  if (typeof form.tagName != 'undefined') {
    requestConfig['data'] = new FormData(form);
  }

  if (cancelToken) {
    requestConfig['cancelToken'] = cancelToken.token;
  }

  return axiosApi(requestConfig).then(({ data }) => {
    handlerNotification(data);
    return data;
  });
}

function handlerNotification(data) {
  const { success, attention, error_warning: errorWarning } = data;
  const message = errorWarning || attention || success || '';
  const type = errorWarning ? 'warning' : 'success';

  if (message && message.trim()) {
    window.notificationMsg(message, type);
  }
}