package evmxgo

import (
	"encoding/hex"
	"fmt"
	"math/rand"
	"os"
	"testing"

	"github.com/33cn/chain33/common/address"
	"github.com/33cn/chain33/common/db"
	types33 "github.com/33cn/chain33/types"
	evmxgotypes "github.com/33cn/plugin/plugin/dapp/evmxgo/types"
	"github.com/stretchr/testify/assert"
	"gitlab.33.cn/link33/sidecar-client-chain33/util"
)

func bytesPrefix(prefix []byte) []byte {
	var limit []byte
	for i := len(prefix) - 1; i >= 0; i-- {
		c := prefix[i]
		if c < 0xff {
			limit = make([]byte, i+1)
			copy(limit, prefix)
			limit[i] = c + 1
			break
		}
	}
	return limit
}

func TestRangGet(t *testing.T) {
	ret := bytesPrefix([]byte("abc"))
	t.Log(ret)
}

func TestDB(t *testing.T) {
	d := db.NewDB("test", "leveldb", os.TempDir(), 100)
	dbList := util.NewKVDBList(d)
	tests := make([]byte, 200, 200)
	for i := range tests {
		key := fmt.Sprintf("mint-%d-%d", i, rand.Int())
		value := []byte(key)
		dbList.Set(value, value)
	}

	datas, _ := dbList.List([]byte("mint-10"), nil, 0, 1)
	for _, data := range datas {
		t.Log(string(data))
	}

	iter := dbList.Iterator(nil, []byte("mint-100"), false)
	for iter.Rewind(); iter.Valid(); iter.Next() {
		t.Log("key:", string(iter.Key()), " value:", string(iter.Value()))
	}
	iter.Close()
}

// https://github.com/Pallinder/go-randomdata：产生随机数据，用于单元测试
// https://github.com/spf13/cast 类型转化

func TestTx(t *testing.T) {
	// data := "0a05746f6b656e1212380c4a0e0a04544553541080e4bbffcac50120a08d0630d5e5e484c9b1a8da4d3a22313268704a4248796268316d537943696a51324d514a506b377a376b5a376a6e5161"
	data := "0a0665766d78676f120e300c220a0a03444f471080ade20420a08d0630c7f8ecc9effcd2ae1b3a2231365542505734757836484e6451444a7051416570746d454c7070414d3936423167"
	td, err := hex.DecodeString(data)
	assert.Nil(t, err)
	tx := &types33.Transaction{}
	err = types33.Decode(td, tx)
	assert.Nil(t, err)
	t.Log(tx)

	params := &evmxgotypes.EvmxgoAction{
		Value: &evmxgotypes.EvmxgoAction_Mint{},
	}
	// payload := &types33.CreateTxIn{}
	// t.Log(hex.EncodeToString(tx.Payload))
	err = types33.Decode(tx.Payload, params)
	t.Log(err)
	assert.Nil(t, err)
	t.Log(params.Ty)
	t.Log(params.Value)
	// t.Log(params.Recipient)
	// t.Log(params.Extra)
	// t.Log(params.BridgeToken)
	// t.Log(payload.ActionName)
	// t.Log(payload.Execer)
	// t.Log(payload.Payload)

	execerAddress := address.ExecAddress(execer)
	t.Log(execerAddress)
	assert.Equal(t, "16UBPW4ux6HNdQDJpQAeptmELppAM96B1g", execerAddress)
}
