import { WebhookBlock } from './WebhookBlock.js';
import { DefaultChannel } from './DefaultChannel.js';
import { MaximumNumberOfMessages } from './MaximumNumberOfMessages.js';
import { DeleteMessage } from './DeleteMessage.js';
import useApiTabWazzupExtensionStore from './../../store/useApiTabWazzupExtensionStore.js';
import useAdditionallyTabWazzupExtensionStore from './../../store/useAdditionallyTabWazzupExtensionStore.js';

export const AdditionallyComponent = {
  name: 'additionally-component',
  components: {
    'webhook-block':   WebhookBlock,
    'default-channel': DefaultChannel,
    'maximum-number-of-messages': MaximumNumberOfMessages,
    'delete-message': DeleteMessage
  },

  setup() {
    const apiStore = useApiTabWazzupExtensionStore();
    const additionallyStore = useAdditionallyTabWazzupExtensionStore();
    const { t } = VueI18n.useI18n();

    return {
      save() {
        let action = 'additionally';
        let payload = {
          webhook_uri: apiStore.webhook_uri,
          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,
        };

        fetch('./api/dev/cbext/clientbase/wazzup/save', {
          method: "POST",
          credentials: 'include',
          headers: {
            'X-Auth-Token': CB.globals.x_auth_token,
            'Content-Type': 'application/vnd.api+json',
          },
          body: JSON.stringify({ action, ...payload }),
        })
        .then(response => {
          if (response.status == 200) {
            window.displayNotification(t('settings_saved'), 1);
            location.reload();
          } else {
            window.displayNotification(t('settings_not_saved'), 2);
          }
        });
      }
    }
  },

  template: /*html*/`
    <div class="wazzup__content">
      <webhook-block />
      <default-channel />
      <maximum-number-of-messages />
      <delete-message />
    </div>

    <hr style="width: 50%;">

    <save-button @click-handle="save" />
  `
}
