const { HDPrivateKey, PrivateKey } = require('bitcore-lib')
const { TemplateWarehouse, Compiler, Contract } = require('@asimovdev/asimovjs')
const readlineSync = require('readline-sync')
const colors = require('colors')
const storage = require('./storage')
const { request, rpc } = require('./rpc')
const path = require('path');
const utils = require('../lib/utils')
let Module = require('../lib/flow_4.0.0')

module.exports = {
  call: function(contractAddress, method, args, gasLimit, amount, asset, privateKey, feeValue, feeType) {
    if (!contractAddress) {
      console.log(colors.yellow('contract address is not specified!'))
      return
    }

    if (!privateKey) {
      console.log(colors.yellow('private key is not specified!'))
      return
    }

    let accounts = storage.getAccount()
    let caller = ''

    if (accounts.length) {
      caller = accounts[0].address
    } else if (privateKey) {
      caller = utils.getAddressByPrivateKey(privateKey)
    } else {
      console.log(colors.yellow('no caller is found!'))
      return
    }

    return new Promise((resolve, reject) => {
      rpc.getContractTemplate(contractAddress).then(res => {
        let templateName = res.template_name
        let category = res.template_type

        rpc.getContractTemplateInfoByName({
          category: category,
          templateName: templateName
        }).then(res => {
          let byteCode = res.byte_code
          let abi = JSON.parse(res.abi)
          let contract = new Contract({
            abi: abi,
            byteCode: byteCode,
            contractAddress: contractAddress,
            chainRpcProvider: rpc
          })

          contract.call({
            methodName: method,
            args: args,
            privateKey: privateKey,
            gasLimit: gasLimit,
            caller: caller,
            amount: amount,
            asset: asset,
            fee: {
              amount: feeValue,
              asset: feeType
            }
          }).then(res => {
            resolve(res)
          }).catch(e => {
            console.log(colors.red(e))
            reject(e)
          })

        }).catch(e => {
          reject(e)
        })
      }).catch(e => {
        reject(e)
      })
    })

  }
}
