<!--
 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>
  <v-flex class="d-flex flex-column border-box-sizing">
    <div class="ms-auto me-8">
      <v-switch
        v-model="seeAll"
        :label="$t('deed.provisioning.seeAll')"
        class="mt-0 pb-1" />
    </div>
    <v-card
      :loading="loading"
      class="flex-grow-1 d-flex"
      flat>
      <v-expansion-panels
        v-if="hasDeeds"
        v-model="openedStatuses"
        class="mb-4"
        multiple
        flat>
        <template v-for="status in defaultStatuses">
          <deed-provisioning-management-tenants-status-panel
            v-if="deedsByStatus[status]"
            :key="status"
            :loading="loadingByStatus[status]"
            :status="status"
            :deeds="deedsByStatus[status]"
            :available-size="sizesByStatus[status]" />
        </template>
      </v-expansion-panels>
      <v-flex v-else-if="!loading" class="d-flex">
        <span class="ma-auto pb-12 headline">{{ $t('deed.provisioning.noOngoingRequestsForNow') }}</span>
      </v-flex>
    </v-card>
    <deed-provisioning-management-tenants-manage-drawer
      :email-templates="emailTemplates" />
    <deed-provisioning-management-tenants-preview-mail-drawer
      :settings="settings" />
  </v-flex>
</template>
<script>
export default {
  props: {
    emailTemplates: {
      type: Array,
      default: () => null,
    },
    settings: {
      type: Object,
      default: null,
    },
  },
  data: () => ({
    loading: true,
    seeAll: false,
    defaultStatuses: [
      'START_CONFIRMED',
      'START_IN_PROGRESS',
      'STOP_CONFIRMED',
      'STOP_IN_PROGRESS'
    ],
    limitByStatus: {
      'START_CONFIRMED': 5,
      'START_IN_PROGRESS': 5,
      'STOP_CONFIRMED': 5,
      'STOP_IN_PROGRESS': 5,
    },
    loadingByStatus: {
      'START_CONFIRMED': false,
      'START_IN_PROGRESS': false,
      'STOP_CONFIRMED': false,
      'STOP_IN_PROGRESS': false,
    },
    deeds: {
      deeds: {
        'START_CONFIRMED': [],
        'START_IN_PROGRESS': [],
        'STOP_CONFIRMED': [],
        'STOP_IN_PROGRESS': [],
      },
      sizes: {
        'START_CONFIRMED': 0,
        'START_IN_PROGRESS': 0,
        'STOP_CONFIRMED': 0,
        'STOP_IN_PROGRESS': 0,
      },
    },
    openedStatuses: [0, 1, 2, 3],
    retrievedDeedsSize: 0,
  }),
  computed: {
    hasDeeds() {
      return this.retrievedDeedsSize > 0;
    },
    deedsByStatus() {
      return this.deeds.deeds;
    },
    sizesByStatus() {
      return this.deeds.sizes || {};
    },
    statuses() {
      return Object.keys(this.deedsByStatus || {});
    },
  },
  watch: {
    seeAll() {
      this.loadMoreByStatus();
    },
  },
  created() {
    this.$root.$on('status-load-more', this.loadMore);
    this.$root.$on('deed.event.tenantStartCommandCreated', this.loadMoreByStatus);
    this.$root.$on('deed.event.tenantStopCommandCreated', this.loadMoreByStatus);
    this.$root.$on('deed.event.tenantCancelCommand', this.loadMoreByStatus);
    this.loadMore().finally(() => this.$root.$applicationLoaded());
  },
  methods: {
    statusChanged(deed) {
      this.$set(this.changedDeeds, deed.nftId, deed);
      this.computeRetrievedDeedsSize();
    },
    loadMoreByStatus() {
      this.loading = true;
      this.defaultStatuses.forEach(status => {
        this.loadMore(status, this.limitByStatus[status]);
      });
    },
    loadMore(status, limit) {
      if (status) {
        this.$set(this.loadingByStatus, status, true);
        if (limit > this.limitByStatus[status]) {
          this.$set(this.limitByStatus, status, limit);
        }
      } else {
        this.loading = true;
      }
      return this.$tenantProvisioningService.getTenants(status, limit, this.seeAll)
        .then(data => {
          if (status) {
            this.deeds.sizes[status] = data?.sizes && data?.sizes[status] || 0;
            this.deeds.deeds[status] = data?.deeds && data?.deeds[status] || [];
          } else {
            if (!data.deeds) {
              data.deeds = {};
            }
            if (!data.sizes) {
              data.sizes = {};
            }
            this.deeds = data;
          }
          return this.deeds;
        })
        .finally(() => {
          this.computeRetrievedDeedsSize();
          return this.$nextTick();
        })
        .then(() => {
          this.$set(this.loadingByStatus, status, false);
          this.loading = Object.values(this.loadingByStatus).filter(loading => !!loading).length > 0;
        });
    },
    computeRetrievedDeedsSize() {
      this.retrievedDeedsSize = Object.values(this.deeds.sizes).reduce((result, value) => result + value, 0);
    },
  }
};
</script>
