package executor

import (
	"github.com/33cn/chain33/types"
	brokertypes "github.com/33cn/plugin/plugin/dapp/broker/types"
)

/*
 * 实现交易相关数据本地执行，数据不上链
 * 非关键数据，本地存储(localDB), 用于辅助查询，效率高
 */

func (b *broker) ExecLocal_RegisterExector(payload *brokertypes.RegisterExector, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
	dbSet := &types.LocalDBSet{}
	//implement code, add customize kv to dbSet...

	//auto gen for localdb auto rollback
	return b.addAutoRollBack(tx, dbSet.KV), nil
}

func (b *broker) ExecLocal_Audit(payload *brokertypes.Audit, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
	dbSet := &types.LocalDBSet{}
	//implement code, add customize kv to dbSet...

	//auto gen for localdb auto rollback
	return b.addAutoRollBack(tx, dbSet.KV), nil
}


func (b *broker) ExecLocal_UpdateIndex(payload *brokertypes.UpdateIndex, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
	dbSet := &types.LocalDBSet{}

	return b.addAutoRollBack(tx, dbSet.KV), nil
}


func (b *broker) ExecLocal_EmitInterchainEvent(payload *brokertypes.InterchainEvent, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
	dbSet := &types.LocalDBSet{}

	return b.addAutoRollBack(tx, dbSet.KV), nil
}

//GetIndex get index
func (b *broker) GetIndex(index int) uint64 {
	return uint64(int(b.GetHeight())*types.MaxTxsPerBlock + index)
}

//当区块回滚时，框架支持自动回滚localdb kv，需要对exec-local返回的kv进行封装
func (b *broker) addAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet {

	dbSet := &types.LocalDBSet{}
	dbSet.KV = b.AddRollbackKV(tx, tx.Execer, kv)
	return dbSet
}
