import (
	"bytes"
	"errors"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/cloudfoundry-incubator/ltc/ssh/sshapi"
	"github.com/cloudfoundry-incubator/ltc/ssh/sshapi/mocks"
)

var _ = Describe("Session", func() {
	var (
		client      *sshapi.Client
		mockSession *mocks.FakeSSHSession
		session     *sshapi.Session
	)

	BeforeEach(func() {
		mockSessionFactory := &mocks.FakeSSHSessionFactory{}
		client = &sshapi.Client{
			SSHSessionFactory: mockSessionFactory,
			Stdin:             &bytes.Buffer{},
			Stdout:            &bytes.Buffer{},
			Stderr:            &bytes.Buffer{},
		}
		mockSession = &mocks.FakeSSHSession{}
		mockSession.StdinPipeReturns(&mockConn{Writer: &bytes.Buffer{}}, nil)
		mockSession.StdoutPipeReturns(&bytes.Buffer{}, nil)
		mockSession.StderrPipeReturns(&bytes.Buffer{}, nil)
	closed bool
}

type nilNetConn struct {
	net.Conn
}

func (m *mockConn) Close() error {
	m.closed = true
	return nil
}

var _ = Describe("Client", func() {
	Describe("#Forward", func() {
		var (
			client     *sshapi.Client
			fakeDialer *mocks.FakeDialer
		)

		BeforeEach(func() {
			fakeDialer = &mocks.FakeDialer{}
			client = &sshapi.Client{Dialer: fakeDialer}
		})

		It("should dial a remote connection", func() {
			localConn := &mockConn{Reader: &bytes.Buffer{}, Writer: &bytes.Buffer{}}
			remoteConn := &mockConn{Reader: &bytes.Buffer{}, Writer: &bytes.Buffer{}}
			fakeDialer.DialReturns(remoteConn, nil)

			Expect(client.Forward(localConn, "some remote address")).To(Succeed())

			Expect(fakeDialer.DialCallCount()).To(Equal(1))