<!--
 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.updateTenantStatusDrawerTitle') }}</h4>
    </template>
    <template #content>
      <v-card flat>
        <v-card-title>
          {{ $t('deeds.provisioning.management.informTenantHostTitle') }}
        </v-card-title>
        <v-card-subtitle>
          {{ $t('deeds.provisioning.management.informTenantHostSubtitle') }}
        </v-card-subtitle>
        <v-card-text>
          <v-label>{{ $t('deeds.provisioning.management.tenantStatus') }}</v-label>
          <v-select
            ref="selectTenantStatus"
            v-model="tenantStatus"
            :items="tenantStatuses"
            :append-icon="tenantStatusIcon"
            class="pt-2"
            outlined
            @click.prevent="openSelection" />
          <v-checkbox
            v-model="sendMail"
            id="sendMailToTenantHost"
            name="sendMailToTenantHost"
            on-icon="fas fa-check-square fa-lg"
            off-icon="far fa-square fa-lg"
            class="ms-n1 mt-2 mb-10">
            <template #label>
              <div class="d-flex flex-column mb-n10 flex-grow-1">
                <div class="mb-2">{{ $t('deeds.provisioning.management.sendEmailCheckbox') }}:</div>
                <div class="mx-auto">
                  <v-chip class="primary--text" outlined>
                    <v-icon class="fa-sm me-2">fas fa-envelope</v-icon>
                    {{ deed.managerEmail }}
                  </v-chip>
                </div>
              </div>
            </template>
          </v-checkbox>
          <template v-if="sendMail">
            <v-label>{{ $t('deeds.provisioning.management.selectEmailTemplate') }}</v-label>
            <v-select
              ref="selectEmailTemplate"
              v-model="emailTemplateId"
              :items="validEmailTemplates"
              class="pt-2"
              item-value="id"
              item-text="name"
              outlined
              @click.prevent="openSelection" />
            <div class="d-flex">
              <v-chip
                v-if="notePage"
                :href="notePage.url"
                :title="notePage.title || notePage.name"
                target="_blank"
                rel="nofollow noreferrer noopener"
                class="primary--text my-2 mx-auto"
                outlined>
                <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>
            </div>
          </template>
        </v-card-text>
      </v-card>
    </template>
    <template #footer>
      <div class="d-flex">
        <v-btn
          v-if="sendMail"
          :disabled="!emailTemplateId"
          min-width="120"
          name="cancelSaveTenant"
          class="btn primary--text me-2"
          outlined
          text
          @click="previewMail">
          <span class="text-capitalize">
            {{ $t('deeds.preview') }}
          </span>
        </v-btn>
        <v-btn
          v-else
          min-width="120"
          name="cancelSaveTenant"
          class="btn ms-auto me-2"
          outlined
          text
          @click="close">
          <span class="text-capitalize">
            {{ $t('deeds.cancel') }}
          </span>
        </v-btn>
        <v-btn
          :loading="sending"
          :class="sendMail && 'ms-auto'"
          min-width="120"
          name="saveTenant"
          class="primary"
          depressed
          dark
          @click="save">
          <span class="text-capitalize">
            {{ sendMail && $t('deeds.saveAndSendMail') || $t('deeds.save') }}
          </span>
        </v-btn>
      </div>
    </template>
  </exo-drawer>
</template>
<script>
export default {
  props: {
    emailTemplates: {
      type: Array,
      default: () => null,
    },
  },
  data: () => ({
    deed: null,
    emailTemplateId: null,
    tenantStatus: null,
    sendMail: false,
    sending: false,
  }),
  computed: {
    validEmailTemplates() {
      return this.emailTemplates?.filter(emailTemplate => !!emailTemplate.notePage);
    },
    emailTemplate() {
      return this.emailTemplates.find(template => template.id === this.emailTemplateId);
    },
    notePage() {
      return this.emailTemplate?.notePage;
    },
    emailSubjectText() {
      return this.emailTemplate?.mailSubject || '';
    },
    emailContentHtml() {
      return this.notePage?.content || '';
    },
    tenantStatuses() {
      return [{
        value: 'UNDEPLOYED',
        text: this.$t('deeds.provisioning.management.tenantstatusUndeployed'),
      }, {
        value: 'DEPLOYED',
        text: this.$t('deeds.provisioning.management.tenantstatusDeployed'),
      }];
    },
    tenantStatusIcon() {
      return this.tenantStatus === 'DEPLOYED' && 'fas fa-thumbs-up success--text fa-xl' || 'fas fa-thumbs-down error--text fa-xl';
    },
  },
  watch: {
    sending() {
      if (this.sending) {
        this.$refs.drawer.startLoading();
      } else {
        this.$refs.drawer.endLoading();
      }
    },
  },
  created() {
    this.$root.$on('open-tenant-management', this.open);
  },
  mounted() {
    this.$refs.drawer.$el.onclick = () => this.closeSelection();
  },
  methods: {
    open(deed) {
      this.deed = deed;
      if (this.deed) {
        this.tenantStatus = this.deed.tenantStatus;
        this.sendMail = false;
        this.$refs.drawer.open();
      }
    },
    close() {
      this.$refs.drawer.close();
    },
    closeSelection() {
      if (this.$refs.selectTenantStatus) {
        this.$refs.selectTenantStatus.isMenuActive = false;
      }
      if (this.$refs.selectEmailTemplate) {
        this.$refs.selectEmailTemplate.isMenuActive = false;
      }
    },
    openSelection(event) {
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }
    },
    previewMail() {
      this.$root.$emit('open-tenant-management-mail-preview', this.deed, this.emailTemplate);
    },
    save() {
      this.sending = true;
      this.saveStatus()
        .then(() => {
          if (this.sendMail) {
            return this.sendMailToHost()
              .catch(error => {
                document.dispatchEvent(new CustomEvent('notification-alert', {detail: {
                  type: 'error',
                  message: this.$t('deeds.provisioning.management.tenantStatusSavedButMailSendingError'),
                }}));
                return error;
              });
          }
        })
        .then(error => {
          if (!error) {
            document.dispatchEvent(new CustomEvent('notification-alert', {detail: {
              type: 'success',
              message:
                this.sendMail
                  && this.$t('deeds.provisioning.management.tenantStatusSavedAndEmailSentSuccessfully')
                  || this.$t('deeds.provisioning.management.tenantStatusSavedSuccessfully')
            }}));
            this.close();
          }
        })
        .catch(() => {
          document.dispatchEvent(new CustomEvent('notification-alert', {detail: {
            type: 'error',
            message:
              this.sendMail
                && this.$t('deeds.provisioning.management.tenantStatusSaveErrorNoMail')
                || this.$t('deeds.provisioning.management.tenantStatusSaveError')
          }}));
        })
        .finally(() => this.sending = false);
    },
    saveStatus() {
      return this.$tenantProvisioningService.saveTenantStatus(this.deed.nftId, this.tenantStatus);
    },
    sendMailToHost() {
      return this.$tenantProvisioningEmailService.sendEmail(this.deed.nftId, this.emailSubjectText, this.emailContentHtml);
    },
  },
};
</script>
