const _ = require('lodash')
const colors = require('colors');
const { ChainRpcProvider, Transactions } = require('@asimovdev/asimovjs')
const storage = require('./storage')
const console = require('./console')

let rpcConfig = storage.getRpcConfig()
let rpc = new ChainRpcProvider({
  baseURL: rpcConfig.url || 'https://test-rpc.asimov.network'
});


function request(method, args) {
  if (method.indexOf('asimov_') == -1) {

    method = 'asimov_' + _.lowerFirst(method)
  }

  return rpc.request(method, args).then(res => {
    return res
  }).catch(err => {
    console.error(err.toString());
  })
}

function checkState(txid, deploy) {
  let transactions = new Transactions(rpc);
  let num = 0;
  this.timer = setInterval(() => {
    if(num < 10) {
      transactions.fetch(txid).then(res => {
        if (res && res.status) {
          if (res.status == "0x1") {
            console.success('success!')
            if(deploy) {
              console.log('contract address:' + res.contractAddress)
            }
          } else {
            console.error('failed!')
          }
          clearInterval(this.timer);
        } else {
          console.log('waiting...')
        }
        num++
      })
    } else {
      console.error('time out!')
      clearInterval(this.timer);
    }
  }, 5000)
}


module.exports = {
  request: request,
  rpc: rpc,
  checkState: checkState
}
