package client

import (
	"crypto/tls"
	"fmt"
	"time"

	"helmet/pkg/mlbctl"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

const (
	DefaultServicePort uint32 = 1027
)

func NewClient(hostinfo string, authCred *AuthCredential) (*grpc.ClientConn, mlbctl.ControlClient, error) {
	var err error
	var cli mlbctl.ControlClient

	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
	}
	const idleTimeout time.Duration = 30 * time.Second
	dialOpts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
		grpc.WithPerRPCCredentials(authCred),
		grpc.WithBlock(),
		grpc.WithIdleTimeout(idleTimeout),
	}
	conn, err := grpc.NewClient(hostinfo, dialOpts...)
	if err != nil {
		return conn, cli, fmt.Errorf("Dial error: %v", err)
	}
	cli = mlbctl.NewControlClient(conn)
	return conn, cli, err
}
