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)
			Expect(remoteConnBuffer.String()).To(Equal("some local data"))
		})

		Context("when dialing a remote connection fails", func() {
			It("should return an error", func() {
				fakeDialer.DialReturns(nil, errors.New("some error"))
				err := client.Forward(nil, "some remote address")
				Expect(err).To(MatchError("some error"))
			})
		})
	})

	Describe("#Open", func() {
		var (
			client             *sshapi.Client
			mockSession        *mocks.FakeSSHSession
			mockSessionFactory *mocks.FakeSSHSessionFactory
			originalTerm       string
		)

		BeforeEach(func() {
			originalTerm = os.Getenv("TERM")
			mockSessionFactory = &mocks.FakeSSHSessionFactory{}
			client = &sshapi.Client{
				SSHSessionFactory: mockSessionFactory,
			}
			mockSession = &mocks.FakeSSHSession{}
			mockSessionFactory.NewReturns(mockSession, nil)
		})

		AfterEach(func() {
			os.Setenv("TERM", originalTerm)