package chain33

import (
	"strings"
	"time"

	"github.com/33cn/chain33/common"
	"github.com/33cn/chain33/common/address"
	"github.com/33cn/chain33/common/crypto"
	client "github.com/33cn/chain33/rpc/grpcclient"
	"github.com/33cn/chain33/types"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
)

func NewGrpcClient(url string) (types.Chain33Client, error) {
	kp := keepalive.ClientParameters{
		Time:                time.Second * 5,
		Timeout:             time.Second * 20,
		PermitWithoutStream: true,
	}
	if url == "" {
		panic("hosts is empty")
	}
	conn, err := grpc.Dial(client.NewMultipleURL(url), grpc.WithInsecure(),
		grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(100*1024*1024)),
		grpc.WithKeepaliveParams(kp))
	if err != nil {
		return nil, err
	}
	return types.NewChain33Client(conn), nil
}

func Getprivkey(key string) crypto.PrivKey {
	cr, err := crypto.Load(types.GetSignName("", types.SECP256K1), -1)
	if err != nil {
		panic(err)
	}
	bkey, err := common.FromHex(key)
	if err != nil {
		panic(err)
	}
	priv, err := cr.PrivKeyFromBytes(bkey)
	if err != nil {
		panic(err)
	}
	return priv
}

func GetEthToLowerAddr(addr string) string {
	if addr == "" {
		return ""
	}
	if address.IsEthAddress(addr) {
		return strings.ToLower(addr)
	}
	return addr
}