<template>
  <div class="row mb-4">
    <div class="col-12">
      <div class="card p-card">
        <h4 class="card-custom-title">
          {{ titleStr }}
        </h4>
        <hr>
        <div v-if="isEarnHistoryInfoCalled">
          <div class="mt-3 overflow-hidden">
            <div class="table-responsive">
              <table class="table rounded rounded-3 table align-middle" style="background-color: var(--grey-custom);">
                <thead>
                  <tr>
                    <th>#</th>
                    <th scope="col">{{ $t(i18nConst.earnCampaignHistoryStart) }}</th>
                    <th scope="col">{{ $t(i18nConst.earnCampaignHistoryEnd) }}</th>
                    <th scope="col">{{ $t(i18nConst.earnAmountHistoryMetadex) }}</th>
                    <th scope="col">{{ $t(i18nConst.earnAmountHistory) }}</th>
                    <th scope="col">{{ $t(i18nConst.earnInterestHistoryMetadex) }}
                      <br><small>({{ $t(i18nConst.earnMinimumClaimable) }}: {{
                        Number(utilsWeb3.formatAmountMetadex(this.minReleasableInterest[this.type][this.version],
                          this.web3)).toFixed(2)
                      }} METADEX)</small>
                    </th>
                  </tr>
                </thead>
                <tbody
                  v-if="(this.earnCampaignsInfo[this.type][this.version]).length == this.earnCampaignsCount[this.type][this.version]">
                  <tr v-for="c in earnCampaignsCount[this.type][this.version]" :key="c">
                    <th scope="row">{{ c }}</th>
                    <td>{{ earnCampaignsInfo[this.type][this.version][c - 1].startDateFormatted }}</td>
                    <td>
                      <div v-if="!earnCampaignsInfo[this.type][this.version][c - 1].renew" class="mb-1">
                        {{ earnCampaignsInfo[this.type][this.version][c - 1].endDateFormatted }}
                      </div>
                      <div v-if="earnCampaignsInfo[this.type][this.version][c - 1].renew">
                        <button @click="cancelRenew(c - 1)" type="button" class="btn btn-meta-1">{{
                          $t(i18nConst.earnCancelRenew)
                        }}</button>
                      </div>
                      <div v-else-if="!isCapitalReleasable(c - 1)">
                        <button @click="activateRenew(c - 1)" type="button" class="btn btn-meta-1">{{
                          $t(i18nConst.earnActivateRenew)
                        }}</button>
                      </div>
                    </td>
                    <td>
                      <div v-if="!isCapitalReleased(c - 1)" class="mb-1">
                        <div>
                          {{ (initialCapitalAmountsMetadex[c - 1]) }}
                          <img v-if="earnCampaignsInfo[this.type][this.version][c - 1].protection" style="height: 2rem" src="../../assets/svg/shield.svg" alt="Protected Campaign" />
                        </div>
                      </div>
                      <div v-if="isCapitalReleasable(c - 1)">
                        <button v-if="!isCapitalReleased(c - 1)" @click="releaseCapital(c - 1)" type="button"
                          class="btn btn-meta-1">{{ $t(i18nConst.earnReleaseCapital) }}</button>
                        <div v-else>
                          <span>{{ $t(i18nConst.earnCapitalReleased) }}</span><br>
                          <span>
                            {{ (initialCapitalAmountsMetadex[c - 1]) }}
                          </span>
                        </div>
                      </div>
                    </td>
                    <td>
                      <div class="mb-1">
                        {{ utilsWeb3.formatAmount(earnCampaignsInfo[this.type][this.version][c - 1].amountUSDC) }} 
                          USDC
                      </div>
                    </td>
                    <td>
                      <div class="mb-1">
                        {{ interestReleased[c - 1] }}
                      </div>
                      <div v-if="isInterestClaimable(c - 1)">
                        <button @click="releaseInterest(c - 1)" type="button" class="btn btn-meta-1">Claim</button>
                      </div>
                    </td>
                  </tr>
                </tbody>
                <!-- tbody for WMATIC CAMPAIGNS -->
                <!-- <tbody v-if="(this.earnCampaignsInfoWMATIC[this.type][this.version]).length == this.earnCampaignsCountWMATIC[this.type][this.version]">
                  <tr v-for="c in earnCampaignsCountWMATIC[this.type][this.version]" :key="c">
                    <th scope="row">{{ c }}</th>
                    <td>{{ earnCampaignsInfoWMATIC[this.type][this.version][c - 1].startDateFormatted }}</td>
                    <td>
                      <div v-if="!earnCampaignsInfoWMATIC[this.type][this.version][c - 1].renew" class="mb-1">
                        {{ earnCampaignsInfoWMATIC[this.type][this.version][c - 1].endDateFormatted }}
                      </div>
                      <div v-if="earnCampaignsInfoWMATIC[this.type][this.version][c - 1].renew">
                        <button @click="cancelRenewWMATIC(c - 1)" type="button" class="btn btn-meta-1">{{
                          $t(i18nConst.earnCancelRenew)
                        }}</button>
                      </div>
                      <div v-else-if="!isCapitalReleasableWMATIC(c - 1)">
                        <button @click="activateRenewWMATIC(c - 1)" type="button" class="btn btn-meta-1">{{
                          $t(i18nConst.earnActivateRenew)
                        }}</button>
                      </div>
                    </td>
                    <td>
                      <div v-if="!isCapitalReleasedWMATIC(c - 1)" class="mb-1">
                        <div >
                          {{ (initialCapitalAmountsMetadexWMATIC[c - 1]) }}
                          <img v-if="earnCampaignsInfoWMATIC[this.type][this.version][c - 1].protection" style="height: 2rem" src="../../assets/svg/shield.svg" alt="Protected Campaign" />
                        </div>
                      </div>
                      <div v-if="isCapitalReleasableWMATIC(c - 1)">
                        <button v-if="!isCapitalReleasedWMATIC(c - 1)" @click="releaseCapitalWMATIC(c - 1)" type="button"
                          class="btn btn-meta-1">{{ $t(i18nConst.earnReleaseCapital) }}</button>
                        <div v-else>
                          <span>{{ $t(i18nConst.earnCapitalReleased) }}</span><br>
                          <span>
                            {{ (initialCapitalAmountsMetadexWMATIC[c - 1]) }}
                          </span>
                        </div>
                      </div>
                    </td>
                    <td>
                      <div class="mb-1">
                        {{ utilsWeb3.formatDisplayAmountWithEthers(earnCampaignsInfoWMATIC[this.type][this.version][c - 1].amountWMATIC, 18) }} 
                          MATIC
                      </div>
                    </td>
                    <td>
                      <div class="mb-1">
                        {{ interestReleasedWMATIC[c - 1] }}
                      </div>
                      <div v-if="isInterestClaimableWMATIC(c - 1)">
                        <button @click="releaseInterestWMATIC(c - 1)" type="button" class="btn btn-meta-1">Claim</button>
                      </div>
                    </td>
                  </tr>
                </tbody> -->
              </table>
            </div>
          </div>
        </div>
        <div v-if="isEarnHistoryActive && !isEarnHistoryInfoCalled" class="empty-card">
          <p class="empty-card-title">
            {{ $t(i18nConst.earnHistoryLoading) }}
          </p>
          <p class="empty-card-description">
            {{ $t(i18nConst.earnHistoryLoadingText) }}
          </p>
        </div>
        <div v-if="!isEarnHistoryActive" class="empty-card">
          <p class="empty-card-title">
            {{ $t(i18nConst.earnNoHistory) }}
          </p>
          <p class="empty-card-description">
            {{ emptyStr }}
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import i18nConstantes from "@/constantes/i18n.constantes.js";
import constantes from "@/constantes/constantes.js";
import { mapGetters } from "vuex";
import typeActions from "../../store/typeActions";
import web3Utils from "../../utils/web3.utils";

export default {
  data() {
    return {
      i18nConst: i18nConstantes,
      constantes: constantes,
      utilsWeb3: web3Utils,

      currentEarnHistoryRound: 1,
      setIntervalId: -1,
    }
  },
  props: {
    titleStr: String,
    type: String,
    version: String,
    emptyStr: String,
  },
  computed: {
    ...mapGetters("earn", [
      "earnCampaignsCount",
      //"earnCampaignsCountWMATIC",
      "earnCampaignsInfo",
      //"earnCampaignsInfoWMATIC",
      "minReleasableInterest",
      //"minReleasableInterestWMATIC",
      "actionInProgress"
    ]),
    ...mapGetters("global", [
      "web3"
    ]),
    initialCapitalAmountsMetadex() {
      const amount = [];
      for (let i = 0; i < this.earnCampaignsCount[this.type][this.version]; i++) {
        if (this.earnCampaignsInfo[this.type][this.version][i]) {
          amount[i] = Number(web3Utils.formatAmountMetadex(this.earnCampaignsInfo[this.type][this.version][i].amountMetadex, this.web3)).toFixed(4);
        }
      }
      return amount;
    },
    // initialCapitalAmountsMetadexWMATIC() {
    //   const amount = [];
    //   for (let i = 0; i < this.earnCampaignsCountWMATIC[this.type][this.version]; i++) {
    //     if (this.earnCampaignsInfoWMATIC[this.type][this.version][i]) {
    //       amount[i] = Number(web3Utils.formatAmountMetadex(this.earnCampaignsInfoWMATIC[this.type][this.version][i].amountMetadex, this.web3)).toFixed(4);
    //     }
    //   }
    //   return amount;
    // },
    interestReleased() {
      const amount = [];
      for (let i = 0; i < this.earnCampaignsCount[this.type][this.version]; i++) {
        if (this.earnCampaignsInfo[this.type][this.version][i]) {
          amount[i] = (Number(web3Utils.formatAmountMetadex(this.earnCampaignsInfo[this.type][this.version][i].releasableInterest, this.web3))).toFixed(4);
        }
      }
      return amount;
    },
    // interestReleasedWMATIC() {
    //   const amount = [];
    //   for (let i = 0; i < this.earnCampaignsCountWMATIC[this.type][this.version]; i++) {
    //     if (this.earnCampaignsInfoWMATIC[this.type][this.version][i]) {
    //       amount[i] = (Number(web3Utils.formatAmountMetadex(this.earnCampaignsInfoWMATIC[this.type][this.version][i].releasableInterest, this.web3))).toFixed(4);
    //     }
    //   }
    //   return amount;
    // },
    isEarnHistoryInfoCalled() {
      if (this.earnCampaignsCount[this.type][this.version] > 0) {
        return this.earnCampaignsInfo[this.type][this.version].length == this.earnCampaignsCount[this.type][this.version] ? true : false;
      } 
      // else if (this.earnCampaignsCountWMATIC[this.type][this.version] > 0) {
      //   return this.earnCampaignsInfoWMATIC[this.type][this.version].length == this.earnCampaignsCountWMATIC[this.type][this.version] ? true : false;
      // } 
      else {
        return false;
      }
    },
    isEarnHistoryActive() {
      return (
        this.earnCampaignsCount[this.type][this.version] > 0 
        //|| this.earnCampaignsCountWMATIC[this.type][this.version] > 0
        ) ? true : false;
    }
  },
  methods: {
    isCapitalReleasable(index) {
      const renewRequirement = !(this.earnCampaignsInfo[this.type][this.version][index].renew);
      const dateRequirement = Date.now() >= new Date(parseInt(this.earnCampaignsInfo[this.type][this.version][index].end) * 1000);
      return renewRequirement && dateRequirement;
    },
    // isCapitalReleasableWMATIC(index) {
    //   const renewRequirement = !(this.earnCampaignsInfoWMATIC[this.type][this.version][index].renew);
    //   const dateRequirement = Date.now() >= new Date(parseInt(this.earnCampaignsInfoWMATIC[this.type][this.version][index].end) * 1000);
    //   return renewRequirement && dateRequirement;
    // },

    isCapitalReleased(index) {
      return this.earnCampaignsInfo[this.type][this.version][index].capitalReleased == this.earnCampaignsInfo[this.type][this.version][index].amountMetadex;
    },
    // isCapitalReleasedWMATIC(index) {
    //   return this.earnCampaignsInfoWMATIC[this.type][this.version][index].capitalReleased == this.earnCampaignsInfoWMATIC[this.type][this.version][index].amountMetadex;
    // },

    isInterestClaimable(index) {
      const result = Number(web3Utils.formatAmountMetadex(this.earnCampaignsInfo[this.type][this.version][index].releasableInterest, this.web3)) > Number(web3Utils.formatAmountMetadex(this.minReleasableInterest[this.type][this.version], this.web3)).toFixed(4);
      return result;
    },
    // isInterestClaimableWMATIC(index) {
    //   const result = Number(web3Utils.formatAmountMetadex(this.earnCampaignsInfoWMATIC[this.type][this.version][index].releasableInterest, this.web3)) > Number(web3Utils.formatAmountMetadex(this.minReleasableInterestWMATIC[this.type][this.version], this.web3)).toFixed(4);
    //   return result;
    // },

    async releaseCapital(index) {
      const id = this.earnCampaignsInfo[this.type][this.version][index].id;
      await this.$store.dispatch(typeActions.releaseCapital, { type: this.type, version: this.version, id: id, index: index });
    },
    // async releaseCapitalWMATIC(index) {
    //   const id = this.earnCampaignsInfoWMATIC[this.type][this.version][index].id;
    //   //console.log("releaseCapitalWMATIC => ", id);
    //   await this.$store.dispatch(typeActions.releaseCapitalWMATIC, { type: this.type, version: this.version, id: id, index: index });
    // },

    async releaseInterest(index) {
      const id = this.earnCampaignsInfo[this.type][this.version][index].id;
      await this.$store.dispatch(typeActions.releaseInterest, { type: this.type, version: this.version, id: id, index: index });
    },
    // async releaseInterestWMATIC(index) {
    //   const id = this.earnCampaignsInfoWMATIC[this.type][this.version][index].id;
    //   //console.log("releaseInterestWMATIC => ", id);
    //   await this.$store.dispatch(typeActions.releaseInterestWMATIC, { type: this.type, version: this.version, id: id, index: index });
    // },

    async activateRenew(index) {
      const id = this.earnCampaignsInfo[this.type][this.version][index].id;
      await this.$store.dispatch(typeActions.activateRenew, { type: this.type, version: this.version, id: id, index: index });
    },
    // async activateRenewWMATIC(index) {
    //   const id = this.earnCampaignsInfoWMATIC[this.type][this.version][index].id;
    //   //console.log("activateRenewWMATIC => ", id);
    //   await this.$store.dispatch(typeActions.activateRenewWMATIC, { type: this.type, version: this.version, id: id, index: index });
    // },

    async cancelRenew(index) {
      const id = this.earnCampaignsInfo[this.type][this.version][index].id;
      await this.$store.dispatch(typeActions.cancelRenew, { type: this.type, version: this.version, id: id, index: index });
    },
    // async cancelRenewWMATIC(index) {
    //   const id = this.earnCampaignsInfoWMATIC[this.type][this.version][index].id;
    //   //console.log("cancelRenewWMATIC => ", id);
    //   await this.$store.dispatch(typeActions.cancelRenewWMATIC, { type: this.type, version: this.version, id: id, index: index });
    // }
  },
  async mounted() {
    this.setIntervalId = setInterval(async () => {
      if (!this.actionInProgress) {
        console.log("10s passed - fetching info");
        await this.$store.dispatch(typeActions.getEarnCampaignsCount, { type: this.type, version: this.version });
        //await this.$store.dispatch(typeActions.getEarnCampaignsCountWMATIC, { type: this.type, version: this.version });
        await this.$store.dispatch(typeActions.getAllEarnCampaigns, { type: this.type, version: this.version });
        //await this.$store.dispatch(typeActions.getAllEarnCampaignsWMATIC, { type: this.type, version: this.version });
      } else {
        console.log('action in progress - info not fetched to avoid rate limit issues');
      }
    }, 10000);
    await this.$store.dispatch(typeActions.getEarnCampaignsCount, { type: this.type, version: this.version });
    //await this.$store.dispatch(typeActions.getEarnCampaignsCountWMATIC, { type: this.type, version: this.version });
    await this.$store.dispatch(typeActions.getAllEarnCampaigns, { type: this.type, version: this.version });
    //await this.$store.dispatch(typeActions.getAllEarnCampaignsWMATIC, { type: this.type, version: this.version });
    await this.$store.dispatch(typeActions.getMinReleasableInterest, { type: this.type, version: this.version });
    //await this.$store.dispatch(typeActions.getMinReleasableInterestWMATIC, { type: this.type, version: this.version });

    //console.log(this.earnCampaignsCountWMATIC, this.earnCampaignsInfoWMATIC);
  },
  beforeUnmount() {
    clearInterval(this.setIntervalId);
  }
}
</script>
<style scoped>
th {
  text-align: center;
}

td+td>div {
  text-align: center;
}

tr {
  height: 5rem;
}

.drop-down-menu-custom {
  overflow-y: auto;
  height: 15rem;
}
</style>