<template>
  <div class="card">
    <h4 class="card-custom-title">
      {{ $t(i18nConst.lotteryBuyTicketsTitle) }}
    </h4>
    <p v-if="showCountDown && !resultLottery" class="card-custom-info">{{ countDownData.d }}d {{countDownData.h}}h {{countDownData.m}}m {{ $t(i18nConst.lotteryBuyTicketsUntil) }}</p>
    <p v-if="!showCountDown && !resultLottery" class="card-custom-info">Draw in progress...</p>
    <p v-if="resultLottery" class="card-custom-info">{{ $t(i18nConst.lotteryBuyTicketsDrawDate) }} : {{ dateEnd }}</p>

    <hr>
    <div class="col-md-12 fs-6 p-card">
      <!-- <p>{{ $t(i18nConst.lotteryBuyTicketsMessage) }}</p> -->
      <form v-if="isLotteryOpen">
        <div class="mb-3">
          <label for="exampleDataList" class="form-label">{{ $t(i18nConst.lotteryBuyTicketsBuy) }}</label> -
          <i>{{ ticketsRemaining }} {{ $t(i18nConst.lotteryBuyTicketsRemaining) }}</i>
          <input class="form-control form-control-lg" type="number" v-model="nbTickets" @change="checkAllowance" />
        </div>
        <div class="mb-3">
          <table class="table table-borderless">
            <tr>
              <td class="text-start">{{ $t(i18nConst.lotteryBuyTicketsCost) }} (METADEXDAO)</td>
              <td class="text-end" v-if="infosLottery">
                {{ formatFromWei(infosLottery.priceTicketInMetadex) }} METADEXDAO
              </td>
            </tr>
            <tr>
              <td class="text-start">{{ $t(i18nConst.lotteryBuyTicketsBulk) }}</td>
              <td class="text-end">{{ formatFromWei(discount) }} METADEXDAO</td>
            </tr>
            <tr>
              <td class="text-start">{{ $t(i18nConst.lotteryBuyTicketsPay) }}</td>
              <td class="text-end">{{ formatFromWei(totalCost) }} METADEXDAO</td>
            </tr>
          </table>
        </div>
        <div class="d-grid gap-2 mb-3">
          <div class="alert alert-danger" v-if="!checkTicketsRemaining()">
            <span>Too many tickets. Limit is {{ constantes.maxTicketsLottery }} per lottery.</span>
          </div>
          <button class="btn btn-meta-1" :class="nbTickets > 0 ? '': 'btn-primary disabled'" type="button" @click="enableLottery"
            v-if="!checkAllowance() && checkTicketsRemaining() && stateLottery != 'enabling'">
            {{ $t(i18nConst.lotteryBuyTicketsEnable) }}
          </button>
          <button class="btn btn-primary" type="button" v-if="stateLottery == 'enabling'">
            {{ $t(i18nConst.lotteryBuyTicketsEnabling) }}
          </button>
          <div v-if="!isWhitelisted" class="ineligibilityMessage">
            {{ $t(i18nConst.lotteryBuyTicketsIneligible) }}
          </div>
          <button class="btn btn-meta-1" :class="nbTickets > 0 ? '': 'btn-primary disabled'" type="button" @click="buyInstantly"
            v-if="checkAllowance() && checkTicketsRemaining() && isWhitelisted">
            {{ $t(i18nConst.lotteryBuyTicketsInst) }}
          </button>
          <button class="btn btn-meta-2" :class="nbTickets > 0 ? '': 'disabled'" type="button" @click="viewEditNumbers"
            v-if="checkAllowance() && checkTicketsRemaining() && isWhitelisted">
            {{ $t(i18nConst.lotteryBuyTicketsView) }}
          </button>
        </div>
      </form>
      <div class="empty-card" v-else>
        <img src="../../assets/lottery_closed.png" class="img-fluid w-50 mt-2" alt="Responsive image">
        <p class="empty-card-title">
          {{ $t(i18nConst.lotteryBuyTicketsEmptyTitle) }}
        </p>
        <p class="empty-card-description">
          {{ $t(i18nConst.lotteryBuyTicketsEmptyDescription) }}
        </p>
      </div>
    </div>
  <popup-tickets v-if="ticketsNumbers" :ticketsNumbers="ticketsNumbers"></popup-tickets>
  </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 popupTickets from "./popupTickets.vue";
import dayjs from "dayjs";
import Web3 from "web3";
import whitelist from "@/constantes/lotteryWhitelist.json";

export default {
  components: { popupTickets },
  data() {
    return {
      i18nConst: i18nConstantes,
      constantes: constantes,
      nbTickets: 1,
      timer: undefined,
      countDownData: {
        d: 0,
        h: 0,
        m: 0
      }
    };
  },

  computed: {
    ...mapGetters("lottery", [
      "infosLottery",
      "stateLottery",
      "ticketsNumbers",
      "isLotteryOpen",
      "ticketsRemaining",
      "resultLottery"
    ]),
    ...mapGetters("global", ["allowance","account"]),
    totalCost() {
      if (this.infosLottery) {
        let totalCost;
        if (parseInt(this.infosLottery.discountDivisor) > 0) {
          totalCost = parseInt(this.infosLottery.priceTicketInMetadex) * this.nbTickets * (parseInt(this.infosLottery.discountDivisor) + 1 - this.nbTickets) / parseInt(this.infosLottery.discountDivisor);
        }
        else {
          totalCost = (this.infosLottery.priceTicketInMetadex) * this.nbTickets;
        }
        return totalCost;
      } else {
        return this.nbTickets;
      }
    },
    discount() {
      if (this.infosLottery) {
        return (parseInt(this.infosLottery.priceTicketInMetadex) * this.nbTickets) - this.totalCost;
      } else {
        return 0;
      }
    },
    dateEnd() {
      if (this.infosLottery) {
        return dayjs.unix(this.infosLottery.endTime);
      } else {
        return "";
      }
    },
    showCountDown() {
      if(this.countDownData.d >= 0 && this.countDownData.h >= 0 && this.countDownData.m >= 0) {
        return true;
      } else {
        return false;
      }
    },
    isWhitelisted() {
      console.log("This account => ", this.account.toLowerCase());
      console.log("Address to lowercase => ", whitelist.whitelistedAddresses.map(address => address.toLowerCase()));
      console.log("Comparison result => ", whitelist.whitelistedAddresses.map(address => address.toLowerCase()).includes(this.account.toLowerCase()));

      return whitelist.whitelistedAddresses.map(address => address.toLowerCase()).includes(this.account.toLowerCase());
    }
  },
  methods: {
    formatFromWei(amount) {
      return amount / Math.pow(10, 18)
    },
    formatToWei(amount) {
      return amount * Math.pow(10, 18)
    },
    enableLottery() {
      let allowanceAmount = Web3.utils.toWei(
        String(this.formatFromWei(this.totalCost)),
        "ether"
      );
      this.$store.dispatch(typeActions.enableLottery, {
        allowanceAmount: allowanceAmount
      });
    },
    buyInstantly() {
      this.$store.dispatch(typeActions.buyTickets, {
        nbTickets: this.nbTickets,
        instantly: true,
      });
    },
    viewEditNumbers() {
      this.$store.dispatch(typeActions.viewEditNumbers, {
        nbTickets: this.nbTickets,
      });
    },
    checkAllowance() {
      console.log(this.allowance);
      return this.allowance < this.totalCost ? false : true;
    },
    checkTicketsRemaining() {
      return this.ticketsRemaining < this.nbTickets ? false : true;
    },
    getCountDownData() {
      if (this.infosLottery && this.isLotteryOpen) {
        const end = dayjs.unix(this.infosLottery.endTime).unix() - dayjs().unix();

        const day = ~~(end/(3600 * 24));
        const hour = ~~((end - day*3600*24)/3600);
        const minutes = ~~((end - day*3600*24 - hour*3600)/60);

        this.countDownData.d = day;
        this.countDownData.h = hour;
        this.countDownData.m = minutes;
      }
    }
  },
  async mounted() {
    await this.$store.dispatch(typeActions.getInfosLottery);
    this.roundSelected = this.lastRoundIndex;
    await this.$store.dispatch(typeActions.getAllowance);

    this.getCountDownData();
    this.timer = setInterval(() => {
      this.getCountDownData();
    }, 60000);
  },
  beforeUnmount() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped>
.text-center {
  text-align: center;
}
.ineligibilityMessage {
  background-color: #ffa500;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}
</style>
