import contracts from "./contracts"
import distributor from "../artifacts/contracts/VirtualDistributor.sol/VirtualDistributor.json"
import {initContractByAbi} from "./utils"
import {BigNumber} from "ethers"

const VIRTUAL_DISTIBUTOR_CONTRACT = 'virtual_distributor'

const abi = () => {
  return distributor.abi
}

const bytecode = () => {
  return distributor.bytecode
}

const deployedAddress = (network : string | number) => {
  if (!contracts[`${network}`]) return null
  return contracts[`${network}`][VIRTUAL_DISTIBUTOR_CONTRACT]
}

const initContract = (contractKey : string, readOnly = true, web3Provider = null) => {
  return initContractByAbi(distributor.abi, contractKey, readOnly, web3Provider)
}

const join = (
  nftContract : string,
  tokenId : number | BigNumber,
  web3Provider = null,
  contractKey = VIRTUAL_DISTIBUTOR_CONTRACT
) => {
  return initContract(contractKey, false, web3Provider)
    .then(contract => contract.join(nftContract, tokenId))
}

const pendingRewards = (
  nftContract : string,
  tokenId : number | BigNumber,
  web3Provider = null,
  contractKey = VIRTUAL_DISTIBUTOR_CONTRACT
) => {
  return initContract(contractKey, true, web3Provider)
    .then(contract => contract.pendingRewards(nftContract, tokenId))
}

const nftInfo = (
  nftContract : string,
  tokenId : number | BigNumber,
  web3Provider = null,
  contractKey = VIRTUAL_DISTIBUTOR_CONTRACT
) => {
  return initContract(contractKey, true, web3Provider)
    .then(contract => contract.nftInfo(nftContract, tokenId))
}

const rewardPerBlock = (
  web3Provider = null,
  contractKey = VIRTUAL_DISTIBUTOR_CONTRACT
) => {
  return initContract(contractKey, true, web3Provider)
    .then(contract => contract.rewardPerBlock())
}

const lockHarvest = (
  nftContract : string,
  tokenId : number | BigNumber,
  web3Provider = null,
  contractKey = VIRTUAL_DISTIBUTOR_CONTRACT
) => {
  return initContract(contractKey, false, web3Provider)
    .then(contract => contract.lockHarvest(nftContract, tokenId))
}

const unlockHarvest = (
  nftContract : string,
  tokenId : number | BigNumber,
  web3Provider = null,
  contractKey = VIRTUAL_DISTIBUTOR_CONTRACT
) => {
  return initContract(contractKey, false, web3Provider)
    .then(contract => contract.unlockHarvest(nftContract, tokenId))
}

const harvest = (
  nftContract : string,
  tokenId : number | BigNumber,
  web3Provider = null,
  contractKey = VIRTUAL_DISTIBUTOR_CONTRACT
) => {
  return initContract(contractKey, false, web3Provider)
    .then(contract => contract.harvest(nftContract, tokenId))
}

export {
  abi,
  bytecode,
  deployedAddress,
  join,
  pendingRewards,
  nftInfo,
  rewardPerBlock,
  harvest,
  lockHarvest,
  unlockHarvest
}
export default {
  abi,
  bytecode,
  deployedAddress,
  join,
  pendingRewards,
  nftInfo,
  rewardPerBlock,
  harvest,
  lockHarvest,
  unlockHarvest
}