package executor

import (
	"fmt"
	"github.com/33cn/chain33/common/db"
	"github.com/33cn/chain33/common/db/table"
	"github.com/33cn/chain33/types"
	ety "github.com/33cn/plugin/plugin/dapp/broker/types"
)

//重新设计表，list查询全部在跨链事件localdb查询中
var opt_broker_event = &table.Option{
	Prefix:  KeyPrefixLocalDB,
	Name:    "broker",
	Primary: "index",
	Index:   []string{"dstServiceID", "status","reqType"},
}


//InterchainEventRow table meta 结构
type InterchainEventRow struct {
	*ety.InterchainEvent
}

//NewInterchainEventRow ...
func NewInterchainEventRow() *InterchainEventRow {
	return &InterchainEventRow{&ety.InterchainEvent{}}
}

//CreateRow ...
func (m *InterchainEventRow) CreateRow() *table.Row {
	return &table.Row{Data: &ety.InterchainEvent{}}
}

//SetPayload 设置数据
func (m *InterchainEventRow) SetPayload(data types.Message) error {
	if txdata, ok := data.(*ety.InterchainEvent); ok {
		m.InterchainEvent = txdata
		return nil
	}
	return ety.ErrData
}

//Get 按照indexName 查询 indexValue
func (m *InterchainEventRow) Get(key string) ([]byte, error) {
	if key == "index" {
		return []byte(fmt.Sprintf("%018d", m.Index)), nil
	} else if key == "dstServiceID" {
		return []byte(fmt.Sprintf("%s", m.GetDstServiceID())), nil
	}else if key == "type" {
		return []byte(fmt.Sprintf("%d", m.GetType())), nil
	}
	return nil, types.ErrNotFound
}
//NewInterchainEventTable
func NewInterchainEventTable(kvdb db.KV) *table.Table {
	rowmeta := NewInterchainEventRow()
	table, err := table.NewTable(rowmeta, kvdb, opt_broker_event)
	if err != nil {
		panic(err)
	}
	return table
}