import useApiTabWazzupExtensionStore from "./../store/useApiTabWazzupExtensionStore.js";
import useAccessTabWazzupExtensionStore from "./../store/useAccessTabWazzupExtensionStore.js";
import useChannelsTabWazzupExtensionStore from "./../store/useChannelsTabWazzupExtensionStore.js";
import useAdditionallyTabWazzupExtensionStore from "./../store/useAdditionallyTabWazzupExtensionStore.js";
import useWordTranslation from "./useWordTranslation.js";


/**
 * Выполнить запрос сохранения настроек модуля
 *
 * @param { object|null } body Данные post запроса
 * @returns void|object|false
 */
export default async function(body) {
  if (body === null) {
    const apiStore     = useApiTabWazzupExtensionStore();
    const accessStore  = useAccessTabWazzupExtensionStore();
    const channelStore = useChannelsTabWazzupExtensionStore();
    const additionallyStore = useAdditionallyTabWazzupExtensionStore();

    body = {
      api_key:      apiStore.api_key,
      webhook_uri:  apiStore.webhook_uri,
      groups:       accessStore.groups,
      users:        accessStore.users,
      channels:     channelStore.channels,
      def_chan_for_reminder:               additionallyStore.def_chan_for_reminder,
      maximum_number_of_messages_per_hour: additionallyStore.maximum_number_of_messages_per_hour,
      delete_days: additionallyStore.delete_days,
    }
  }

  let response = await fetch('./api/dev/cbext/clientbase/wazzup/save', {
    credentials: 'include',
    method: 'POST',
    headers: {
      'X-Auth-Token': CB.globals.x_auth_token,
      'Content-Type': 'application/vnd.api+json',
    },
    body: JSON.stringify(body),
  });

  // TODO: добавить обработку ошибок со стороны сервера

  if (await response.text() === 'saved') { // TODO: избавиться от этой гадости
    window.displayNotification(useWordTranslation('succes_settings_save'), 1);
    location.reload();
  } else if (response.ok) {
    return await response.json();
  } else {
    window.displayNotification(useWordTranslation('Saving_error'), 2);
    return false;
  }
}
