package elasticache

import (
	"bufio"
	"net"

	log "github.com/Sirupsen/logrus"
	"github.com/pkg/errors"
)

type conn struct {
	nc net.Conn
	rw *bufio.ReadWriter
}

func connect(endpoint string) (*conn, error) {
	nc, err := net.Dial("tcp", endpoint)
	if err != nil {
		return nil, errors.Wrapf(err,
			"Couldn't connect to ElastiCache configuration endpoint %q", endpoint)
	}

	if err := nc.(*net.TCPConn).SetKeepAlive(true); err != nil {
		log.Warn("Couldn't set TCP keep-alive on connection: ", err)
	}

	rw := bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc))

	return &conn{
		nc: nc,
		rw: rw,
	}, nil
}

func (c *conn) Close() {
	if err := c.nc.Close(); err != nil {
		log.Error(err)
	}
}
