import ABI from '../abi/Erc20';
import { ethers } from 'ethers'
import { MaxUint256 } from '@ethersproject/constants';

let Web3 = require('web3')
let _web3;
let walletMgr;
let codeEnum;
function init (provider,_walletMgr) {
    walletMgr = _walletMgr;
    codeEnum = walletMgr.ReturnCodeEnum;
    _web3 = new Web3(provider);
    
}

async function createcontract(){
    _web3.eth.sendTransaction({from:walletMgr.currentAccount,gasPrice:10000000000,data:"[encoded data, 5920 characters]"})
    .on('transactionHash', function(hash){
        console.log("hash:",hash)
    })
    .on('receipt', function(receipt){
        console.log("receipt:",receipt)
    })
    .on('error', function(error, receipt) {
        console.log("error:",error)
        console.log("receipt:",receipt)
    })
}

async function getTokenInfo(address){
    let contract = new _web3.eth.Contract(ABI, address)
    let symbol = await contract.methods.symbol().call();
    console.log(symbol)
    let decimals = await contract.methods.decimals().call();
    console.log(decimals)
    return {address:address,symbol:symbol,decimals:decimals,image:""};
}

async function isApprovalForAll(address,to,fun){
    let contract = new _web3.eth.Contract(ABI, address)
    let balance = await contract.methods.balanceOf(walletMgr.currentAccount).call();
    let allowance = await contract.methods.allowance(walletMgr.currentAccount,to).call();
    console.log(balance,allowance);
    let balaneEth = ethers.BigNumber.from(balance)
    let allowanceEth = ethers.BigNumber.from(allowance)
    console.log(balaneEth,allowanceEth);
    fun({ code: codeEnum.SUCCESS, data: balaneEth.lte(allowanceEth) })
    
}

async function setApprovalForAll(address,to,fun,fun2){
    let contract = new _web3.eth.Contract(ABI, address)
    // let approveAmount = contract.methods.totalSupply().call();
    // console.log("approve",approveAmount);
    console.log("MaxUint256",MaxUint256);
    await contract.methods.approve(to, MaxUint256).send({
        from: walletMgr.currentAccount,
    })
    .on('transactionHash', function(hash){
        if (fun != null) fun({code:codeEnum.SUCCESS,data:hash})
    })
    .on('receipt', function(receipt){
        fun2({code:codeEnum.SUCCESS,data:receipt});
    })
    .on('error', function(error, receipt) {
        if(receipt == null){
           if (fun != null) fun(error)
        }else{
            if(fun2 != null) fun2({code:codeEnum.CONTRACT_ERROR,data:receipt})
        }
    })
}

export default {
    init,
    setApprovalForAll,
    getTokenInfo,
    isApprovalForAll,
    createcontract,
}
