import { useState, useEffect } from 'react'
import "../css/Banner.css";
import "../css/Beneficiary.css";
import CardBeneficiary from "./CardBeneficiary.jsx";
import eth from "../eth/eth.js"
import {ethers} from "ethers";

function Beneficiary() {

  const [will_beneficiary, setwill_beneficiary] = useState([
  ])

  useEffect(() => {
      getBeneficiaries();
  },[])

  async function wait(time) {
    return new Promise(resolve => setTimeout(resolve, time));
  }

  async function waitForInit() {
    while(!eth.contractWithSigner) {
      console.log("Waiting for 1s")
      await wait(1000);
      console.log("1s over");
    }
  }

  async function getBeneficiaries() {
    await waitForInit();
    console.log(window.ethereum.selectedAddress);
    console.log(eth.contractWithSigner);
    var response = await eth.contractWithSigner.get_wills_beneficiary(window.ethereum.selectedAddress);
    console.log(response);
    console.log(response.length);
    var myBeneficiary = [];
    for(var i=0; i<response.length; i++) {
      var will_beneficiary = await eth.contractWithSigner.wills(response[i].toNumber());
      //console.log(response[i].toNumber());

      try{
        var withdrawdateNew = timeConverter(will_beneficiary.withdrawDate.toNumber());
        var myWill = {
          id: response[i].toNumber(),
          amount: ethers.utils.formatEther(will_beneficiary.amount),
          testator: will_beneficiary.testator,
          beneficiary: will_beneficiary.beneficiary,
          withdrawDate: withdrawdateNew
        }
      }
      catch(e) {
        console.log("Invalid withdrawDate");
        var myWill = {
          id: response[i].toNumber(),
          amount: ethers.utils.formatEther(will_beneficiary.amount),
          testator: will_beneficiary.testator,
          beneficiary: will_beneficiary.beneficiary,
          withdrawDate: "Invalid withdrawDate: "  + will_beneficiary.withdrawDate._hex
        }

      }

            console.log(myWill)
      myBeneficiary.push(myWill);
    }
    setwill_beneficiary(myBeneficiary);


  }

  function timeConverter(withdrawDate){
    var a = new Date(withdrawDate * 1000);
    var year = a.getFullYear();
    var month = a.getMonth()+1;
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    var sec = a.getSeconds();

    if(sec<10){
      sec= '0' + sec;
    }
    if(min<10) {
      min = "0" + min;
    }
    if(month<10){
      month= '0' + month;
    }
    var time = date + '.' + month + '.' + year + ' ' + hour + ':' + min + ':' + sec ;
    return time;
  }

  return (
    <div className="Beneficiary">
      <div className="BeneficiaryContainer">
       {(will_beneficiary).map((item, index) =>
        <CardBeneficiary id={item.id} testator={item.testator} beneficiary={item.beneficiary} withdrawDate={item.withdrawDate} amount={item.amount} key={index}/>
        )}
      </div>
    </div>
  )
}

export default Beneficiary
