import { tokenAbi } from "../tokenAbi"
import { ethers,formatEther,parseEther } from "ethers";

const contractAddress = "0x1ebA64fDe3BF54545c86B9e3bB40c72f50f8D012";
const abi = [{"inputs": [{"internalType": "address","name": "token","type": "address"},{"internalType": "address[]","name": "addresses","type": "address[]"},{"internalType": "uint256[]","name": "amounts","type": "uint256[]"},{"internalType": "bool","name": "isToken","type": "bool"}],"name": "batchTransferFrom","outputs": [{"internalType": "bool","name": "","type": "bool"}],"stateMutability": "payable","type": "function"}]


export const multisend = async (tokenAddress, provider, from, toArray, amountArray) => {
    let totalAmount = 0;
    let isToken = true;
    let status;

    //console.log(tokenAddress, provider, from)

    amountArray.map((row)=> totalAmount += parseFloat(formatEther(row)));

    const signer = await provider.getSigner();
    const contract = new ethers.Contract(contractAddress, abi, signer);

    if(toArray.length !== 0 && amountArray.length !== 0 && toArray.length === amountArray.length)
    {
      try {
        const tokenContract = new ethers.Contract(tokenAddress, tokenAbi, signer); 
        let allowance = isToken ? await tokenContract.allowance(from, contractAddress) : 0;
        let balance = isToken ? await tokenContract.balanceOf(from) : await provider.getBalance(from);
        
        if(balance >= parseEther(totalAmount.toString())){
          if( isToken && allowance < parseEther(totalAmount.toString()))
          {
            const tx = await tokenContract.approve(
              contractAddress,
              parseEther(totalAmount.toString())
            )
            await provider.waitForTransaction(tx.hash);
          }
          } else {
          throw new Error("잔액부족")
        }
      } catch (error) {
        alert(error)
      }

      try {
        const tx = await contract.batchTransferFrom(
          tokenAddress,
          toArray,
          amountArray,
          isToken,
          {value : isToken ? 0 : parseEther(totalAmount.toString())}
        );

        status = await provider.waitForTransaction(tx.hash);  
      } catch (error) {
        console.log(error)        
      }
    } else {
      alert("양식이 맞지 않습니다.")
    }
  
    
    return status;
}

export const getBalance = async (tokenAddress, provider, address) => {
    const signer = await provider.getSigner();

    const tokenContract = new ethers.Contract(tokenAddress, tokenAbi, signer); 

    let balance =  await tokenContract.balanceOf(address)
   
    return balance;
}