package net

import (
	"context"
	"net"
	"syscall"
	"time"

	"golang.org/x/sys/unix"
)

type Dialer interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

func DialContextTCP(ctx context.Context, address string, d Dialer) (net.Conn, error) {
	return d.DialContext(ctx, "tcp", address)
}

func newDefaulDialer() net.Dialer {
	// From `grpc.WithContextDialer` comment:
	//
	// Note: All supported releases of Go (as of December 2023) override the OS
	// defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive
	// with OS defaults for keepalive time and interval, use a net.Dialer that sets
	// the KeepAlive field to a negative value, and sets the SO_KEEPALIVE socket
	// option to true from the Control field. For a concrete example of how to do
	// this, see internal.NetDialerWithTCPKeepalive().
	//
	// https://github.com/grpc/grpc-go/blob/830135e6c5a351abf75f0c9cfdf978e5df8daeba/dialoptions.go#L432
	return net.Dialer{
		KeepAlive: time.Duration(-1),
		Control: func(_, _ string, c syscall.RawConn) error {
			return c.Control(func(fd uintptr) {
				_ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1)
			})
		},
	}
}