const Environment = require('./environment.js')
const U256 = require('./u256.js')

module.exports = class TestEnvironment extends Environment {
  constructor (data) {
    super()
  
    if (typeof data === 'string') {
      data = JSON.parse(data)
    }

    let self = this

    if (data.accounts) {
      data.accounts.forEach((account) => {
        self.state.set(new Uint8Array(account[0]).toString(), account[1])
      })
    }

    if (data.address) {
      self.address = new Uint8Array(data.address)
    }

    if (data.origin) {
      self.origin = new Uint8Array(data.origin)
    }

    if (data.caller) {
      self.caller = new Uint8Array(data.caller)
    }

    if (data.coinbase) {
      self.coinbase = new Uint8Array(data.coinbase)
    }

    if (data.callValue) {
      self.callValue = new U256(data.callValue)
    }

    if (data.callData) {
      self.callData = hexStr2arrayBuf(data.callData)
    }

    if (data.gasPrice) {
      self.gasPrice = data.gasPrice
    }

    if (data.gasLimit) {
      self.gasLimit = data.gasLimit
    }
  }
}

function hexStr2arrayBuf (string) {
  const view = new Uint8Array(string.length / 2)
  string = [...string]
  let temp = ''
  string.forEach((el, i) => {
    temp += el
    if (i % 2) {
      view[(i + 1) / 2 - 1] = parseInt(temp, 16)
      temp = ''
    }
  })
  return view
}

@@ -74,16 +74,56 @@
 256.js')
+%0Aconst Address = require('./address.js')
 %0A%0Amodule
@@ -400,24 +400,36 @@
 ate.set(new 
+Address(new 
 Uint8Array(a
@@ -438,16 +438,17 @@
 ount%5B0%5D)
+)
 .toStrin
@@ -525,24 +525,36 @@
 dress = new 
+Address(new 
 Uint8Array(d
@@ -565,16 +565,17 @@
 address)
+)
 %0A    %7D%0A%0A
@@ -617,24 +617,36 @@
 rigin = new 
+Address(new 
 Uint8Array(d
@@ -656,16 +656,17 @@
 .origin)
+)
 %0A    %7D%0A%0A
@@ -708,24 +708,36 @@
 aller = new 
+Address(new 
 Uint8Array(d
@@ -747,16 +747,17 @@
 .caller)
+)
 %0A    %7D%0A%0A

use Address type