package gateway

import (
	"net"
	"time"
)

type Conn struct {
	buf  []byte
	conn net.Conn
}

func (c *Conn) Read(b []byte) (n int, err error) {
	var m int
	if len(c.buf) > 0 {
		if len(b) >= len(c.buf) {
			m = copy(b[:], c.buf[:])
			c.buf = c.buf[m:]
		}
	}
	n, err = c.conn.Read(b[m:])
	n += m
	return
}

func (c *Conn) Write(b []byte) (n int, err error) {
	return c.conn.Write(b)
}

func (c *Conn) Close() error {
	return c.conn.Close()
}

func (c *Conn) LocalAddr() net.Addr {
	return c.conn.LocalAddr()
}

func (c *Conn) RemoteAddr() net.Addr {
	return c.conn.RemoteAddr()
}

func (c *Conn) SetDeadline(t time.Time) error {
	return c.conn.SetDeadline(t)
}

func (c *Conn) SetReadDeadline(t time.Time) error {
	return c.conn.SetReadDeadline(t)
}

func (c *Conn) SetWriteDeadline(t time.Time) error {
	return c.conn.SetWriteDeadline(t)
}

func wrapConn(c net.Conn, buf []byte) net.Conn {
	conn := &Conn{conn: c, buf: buf}
	if buf != nil {
		conn.buf = make([]byte, len(buf))
		copy(conn.buf, buf)
	}
	return conn
}
