package template

import (
	"fmt"
)

type Template interface {
	InitDriver(parm interface{}) bool
	CreateAddress(parm interface{}) ([]byte, error)
	CoinBalance(parm interface{}) ([]byte, error)
	TransInfo(parm interface{}) ([]byte, error)
	TransferAccounts(parm interface{}) ([]byte, error)
	ChainHeight(parm interface{}) ([]byte, error)
	ListUnspent(parm interface{}) ([]byte, error)
	SendRawTransaction(parm interface{}) ([]byte, error)
}

const (
	CREATEADDR  = "/coinproxy/createaddr"
	TRANSINFO   = "/coinproxy/query/transinfo"
	COINBALANCE = "/coinproxy/coinbalance"
	SENDCOINS   = "/coinproxy/sendcoins"
	CHAINHEIGHT = "/coinproxy/blockchain/height"
	LISTUNSPENT = "/coinproxy/listunspent"
	RAWTRANSFER = "/coinproxy/sendrawtransaction"
)

var Handler = map[string]func(Template, interface{}) ([]byte, error){
	CREATEADDR:  Template.CreateAddress,
	COINBALANCE: Template.CoinBalance,
	SENDCOINS:   Template.TransferAccounts,
	TRANSINFO:   Template.TransInfo,
	CHAINHEIGHT: Template.ChainHeight,
	LISTUNSPENT: Template.ListUnspent,
	RAWTRANSFER: Template.SendRawTransaction,
}
var drivers = make(map[string]Template)

func Register(name string, driver Template) {
	if driver == nil {
		panic("crypto: Register driver is nil")
	}
	if _, dup := drivers[name]; dup {
		fmt.Println("crypto: Register called twice for driver " + name)
		return
	}
	drivers[name] = driver

}

func New(name string) (c Template, err error) {
	c, ok := drivers[name]
	if !ok {
		err = fmt.Errorf("unknown driver %q", name)
		return
	}
	return c, nil
}
