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

function Testator() {

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

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

  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 getWillsTestator() {
    await waitForInit();
    var response = await eth.contractWithSigner.get_wills_testator(window.ethereum.selectedAddress);
    console.log(response);
    var myWills = [];
    for(var i=0; i<response.length; i++) {
      console.log(response[i].toNumber());
      var will_testator = await eth.contractWithSigner.wills(response[i].toNumber());

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

  function timeConverter(withdrawDate){
    var a = new Date(withdrawDate * 1000);
    //var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    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="Testator">
      <div className="TestatorContainer">
       {(will_beneficiary).map((item, index) =>
        <CardTestator id={item.id} testator={item.testator} beneficiary={item.beneficiary} withdrawDate={item.withdrawDate} amount={item.amount} key={index}/>
       )}
      </div>
    </div>
  )
}



export default Testator
