<!--
 This file is part of the Meeds project (https://meeds.io/).
 
 Copyright (C) 2020 - 2022 Meeds Association contact@meeds.io
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 3 of the License, or (at your option) any later version.
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.
 
 You should have received a copy of the GNU Lesser General Public License
 along with this program; if not, write to the Free Software Foundation,
 Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
-->
<template>
  <exo-drawer
    ref="drawer"
    v-model="drawer"
    right>
    <template #title>
      <h4>{{ $t('deeds.provisioning.management.emailTemplateDrawerTitle') }}</h4>
    </template>
    <template #content>
      <v-card
        :loading="loading"
        class="px-6 py-4"
        flat>
        <form ref="form" @submit="event.preventDefault(); return false;">
          <v-label for="emailTemplateName">{{ $t('deeds.provisioning.management.emailTemplateName') }}</v-label>
          <v-text-field
            id="emailTemplateName"
            v-model="emailTemplateName"
            :placeholder="$t('deeds.provisioning.management.emailTemplateNamePlaceholder')"
            label=""
            class="border-box-sizing mt-2 mb-4 py-0"
            name="emailTemplateName"
            type="text"
            aria-required="true"
            autofocus="autofocus"
            required="required"
            outlined
            dense />
          <v-label for="emailSenderEmail">{{ $t('deeds.provisioning.management.emailTemplateDescription') }}</v-label>
          <v-text-field
            id="emailTemplateDescription"
            v-model="emailTemplateDescription"
            :placeholder="$t('deeds.provisioning.management.emailTemplateDescriptionPlaceholder')"
            label=""
            class="border-box-sizing mt-2 mb-4 py-0"
            name="emailTemplateDescription"
            type="text"
            aria-required="true"
            required="required"
            outlined
            dense />
          <v-label for="emailSubject">{{ $t('deeds.provisioning.management.emailSubject') }}</v-label>
          <v-text-field
            id="emailSubject"
            v-model="emailSubject"
            :placeholder="$t('deeds.provisioning.management.emailSubjectPlaceholder')"
            label=""
            class="border-box-sizing mt-2 mb-4 py-0"
            name="emailSubject"
            type="text"
            aria-required="true"
            required="required"
            outlined
            dense />
          <v-label for="emailSubject">
            {{ $t('deeds.provisioning.management.emailTemplateAttachedNotePage') }}
            <v-btn
              :title="$t('deeds.provisioning.management.attachEmailTemplateWithNotePage')"
              icon
              text
              @click="openNotePagesDrawer">
              <v-icon
                color="primary"
                class="ms-1 me-2"
                size="16"
                left>
                fa fas fa-link
              </v-icon>
            </v-btn>
          </v-label>
          <div class="d-flex my-8">
            <v-chip
              v-if="notePage"
              :href="notePage.url"
              :title="notePage.title || notePage.name"
              :close-label="$t('deeds.provisioning.management.detachEmailTemplateWithNotePage')"
              target="_blank"
              rel="nofollow noreferrer noopener"
              class="primary--text my-2 mx-auto"
              close-icon="fa fa-unlink error--text subtitle-2"
              close
              outlined
              @click:close="deleteAttachedNotePage">
              <v-icon
                class="ms-1 me-2"
                size="16"
                left>
                fas fa-clipboard
              </v-icon>
              <div class="text-truncate">{{ notePage.title || notePage.name }}</div>
            </v-chip>
            <v-alert
              v-else
              type="info"
              elevation="0"
              class="position-static ps-0"
              outlined>
              {{ $t('deeds.provisioning.management.emailTemplateNoAttachedNotePage') }}
            </v-alert>
          </div>
          <v-label>{{ $t('deeds.provisioning.management.linkAutomaticEventToStatus') }}</v-label>
          <v-select
            ref="selectAutomaticStatuses"
            v-model="automaticStatus"
            :items="$root.automaticStatuses"
            class="pt-2"
            outlined
            @click.prevent="openSelection" />
        </form>
      </v-card>
    </template>
    <template #footer>
      <div class="d-flex">
        <v-btn
          :disabled="sending"
          :min-width="minButtonsWidth"
          name="cancelEmailSettingsButton"
          class="btn ms-auto me-2"
          outlined
          text
          @click="close">
          <span class="text-capitalize">
            {{ $t('deeds.cancel') }}
          </span>
        </v-btn>
        <v-btn
          :disabled="!validForm"
          :loading="sending"
          :min-width="minButtonsWidth"
          name="saveEmailSettingsButton"
          class="primary"
          depressed
          dark
          @click="save">
          <span class="text-capitalize">
            {{ isNew && $t('deeds.create') || $t('deeds.update') }}
          </span>
        </v-btn>
      </div>
    </template>
  </exo-drawer>
</template>
<script>
export default {
  data: () => ({
    minButtonsWidth: 120,
    emailTemplate: {},
    emailTemplateName: null,
    emailTemplateDescription: null,
    emailSubject: null,
    automaticStatus: null,
    notePage: null,
    sending: false,
    drawer: false,
  }),
  watch: {
    sending() {
      if (this.sending) {
        this.$refs?.drawer?.startLoading();
      } else {
        this.$refs?.drawer?.endLoading();
      }
    },
    drawer() {
      if (this.drawer) {
        this.reset();
      }
    },
  },
  computed: {
    validForm() {
      return this.emailTemplateName?.length
          && this.emailTemplateDescription?.length
          && this.emailSubject?.length;
    },
    isNew() {
      return !this.emailTemplate?.id;
    },
  },
  created() {
    this.$root.$on('deed-email-template-edit', this.open);
  },
  mounted() {
    this.$refs.drawer.$el.onclick = () => this.closeSelection();
  },
  methods: {
    open(emailTemplate) {
      this.emailTemplate = emailTemplate || null;
      this.$refs.drawer.open();
    },
    close() {
      this.$refs.drawer.close();
    },
    reset() {
      this.emailTemplateName = this.emailTemplate?.name;
      this.emailTemplateDescription = this.emailTemplate?.description;
      this.emailSubject = this.emailTemplate?.mailSubject;
      this.automaticStatus = this.emailTemplate?.automaticStatus || 'NONE';
      this.notePage = this.emailTemplate?.notePage;
      this.sending = false;
      this.$refs?.drawer?.endLoading();
    },
    deleteAttachedNotePage() {
      this.notePage = null;
    },
    openNotePagesDrawer() {
      this.$root.$emit('open-note-tree',
        this.notePage,
        notePage => this.selectNotePage(notePage),
      );
    },
    selectNotePage(notePage) {
      if (notePage) {
        this.$notesService.getNoteById(notePage.id)
          .then(data => {
            this.notePage = data;
            this.notePageId = data?.id;
          });
      } else {
        this.notePage = null;
      }
    },
    save() {
      if (!this.$refs.form.reportValidity()) {
        return;
      }
      if (this.emailTemplate) {
        const emailTemplate = Object.assign({}, this.emailTemplate);
        emailTemplate.name = this.emailTemplateName;
        emailTemplate.description = this.emailTemplateDescription;
        emailTemplate.mailSubject = this.emailSubject;
        emailTemplate.automaticStatus = this.automaticStatus || 'NONE';
        emailTemplate.notePageId = this.notePage?.id || 0;
        this.sending = true;
        return this.$tenantProvisioningEmailService.updateEmailTemplate(emailTemplate)
          .then(() => {
            document.dispatchEvent(new CustomEvent('notification-alert', {detail: {
              type: 'success',
              message: this.$t('deeds.provisioning.management.emailTemplateUpdated'),
            }}));
            this.$root.$emit('load-email-templates');
            this.close();
          })
          .catch(() => 
            document.dispatchEvent(new CustomEvent('notification-alert', {detail: {
              type: 'error',
              message: this.$t('deeds.provisioning.management.emailTemplateSaveError'),
            }}))
          )
          .finally(() => this.sending = false);
      } else {
        const emailTemplate = {
          name: this.emailTemplateName,
          description: this.emailTemplateDescription,
          mailSubject: this.emailSubject,
          automaticStatus: this.automaticStatus || 'NONE',
          notePageId: this.notePage?.id || 0,
        };
        this.sending = true;
        return this.$tenantProvisioningEmailService.createEmailTemplate(emailTemplate)
          .then(() => {
            document.dispatchEvent(new CustomEvent('notification-alert', {detail: {
              type: 'success',
              message: this.$t('deeds.provisioning.management.emailTemplateCreated'),
            }}));
            this.$root.$emit('load-email-templates');
            this.close();
          })
          .catch(() => 
            document.dispatchEvent(new CustomEvent('notification-alert', {detail: {
              type: 'error',
              message: this.$t('deeds.provisioning.management.emailTemplateSaveError'),
            }}))
          )
          .finally(() => this.sending = false);
      }
    },
    closeSelection() {
      if (this.$refs.selectAutomaticStatuses) {
        this.$refs.selectAutomaticStatuses.isMenuActive = false;
      }
    },
    openSelection(event) {
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }
    },
  },
};
</script>