package exchainclient

import (
	"context"
	"github.com/exchain/go-exchain/exchain"
	nodev1 "github.com/exchain/go-exchain/exchain/protocol/gen/go/node/v1"
	"github.com/exchain/go-exchain/exchain/wrapper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"math/big"
)

type ExClient struct {
	ins  nodev1.NodeClient
	conn *grpc.ClientConn
}

func NewExClient(server string) (*ExClient, error) {
	conn, err := grpc.Dial(server, grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultCallOptions(
			grpc.MaxCallRecvMsgSize(1024*1024*1024),
			grpc.MaxCallSendMsgSize(1024*1024*1024))) // Use WithTransportCredentials for TLS
	if err != nil {
		return nil, err
	}
	client := nodev1.NewNodeClient(conn)
	return &ExClient{ins: client, conn: conn}, nil
}

func (e *ExClient) BlockByNumber(ctx context.Context, number *big.Int) (*wrapper.BlkWrapper, error) {
	req := &nodev1.GetBlockRequest{
		Number: number.Uint64(),
	}
	res, err := e.ins.GetBlockByNumber(ctx, req)
	if err != nil {
		return nil, err
	}
	return wrapper.NewBlkWrapper(res.Block), nil
}

func (e *ExClient) GetWithdrawalProof(ctx context.Context, param exchain.ExChainWithdrawalParam) ([]string, error) {
	req := &nodev1.WithdrawalProofRequest{
		Txhash: param.TxHash.String(),
	}
	res, err := e.ins.GetWithdrawalProof(ctx, req)
	if err != nil {
		return nil, err
	}
	return res.Proof, nil
}

func (e *ExClient) Close() {
	e.conn.Close()
	return
}
