const { PrivateKey } = require('bitcore-lib')
const {Address} = require('@asimovdev/asimovjs')
const { hexlify, toUtf8Bytes } = require('@spinlee/ethers/utils')
const { Base64 } = require('js-base64')

module.exports = {
  getAddressByPrivateKey(pk) {
    let privateKey = new PrivateKey(pk)
    let address = new Address(privateKey.publicKey);
    return address.toString();
  },

  convert(type, value) {
    switch (type.type) {
      case 'bytes4':
      case 'bytes8':
      case 'bytes16':
      case 'bytes32':
        return hexlify(value)
      case 'bytes':
        return hexlify(toUtf8Bytes(Base64.decode(value)))
      case 'tuple[]':
        type.components.forEach(c => {
          value[c.name] = convert(c, value[c.name])
        })
        return value
      default:
        return value
    }
  },

  callResultConvert(types, values) {
    let result = []
    if (!types.length) {
      return []
    }
    if (!Array.isArray(values)) {
      values = [values]
    }
    types.forEach((t, idx) => {
      let value = values[idx]
      result.push(this.convert(t, value))
    })

    return result
  }
}
