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

	"github.com/cloudfoundry/bosh-init/installation"
	"github.com/cloudfoundry/bosh-utils/logger"
	"github.com/cloudfoundry/bosh-utils/system"
	"github.com/cloudfoundry/bosh-utils/system/fakes"
	"github.com/onsi/gomega/gbytes"
)

var _ = Describe("Uninstaller", func() {
	Describe("Uninstall", func() {
		It("deletes the installation target directory", func() {
			logBuffer := gbytes.NewBuffer()
			goLogger := log.New(logBuffer, "", log.LstdFlags)
			boshlogger := logger.New(logger.LevelInfo, goLogger, goLogger)

			fs := system.NewOsFileSystem(boshlogger)
			installationPath, err := fs.TempDir("some-installation-dir")
			Expect(err).ToNot(HaveOccurred())

			err = fs.WriteFileString(filepath.Join(installationPath, "some-installation-artifact"), "something-blah")
			Expect(err).ToNot(HaveOccurred())

			installationTarget := installation.NewTarget(installationPath)

			uninstaller := installation.NewUninstaller(fs, boshlogger)

			Expect(fs.FileExists(installationPath)).To(BeTrue())

			err = uninstaller.Uninstall(installationTarget)
		BeforeEach(func() {
			manifest.Registry = biinstallmanifest.Registry{
				Username: "******",
				Password: "******",
				Host:     "fake-host",
				Port:     123,
			}

			spy = test_support_mocks.NewMockSpy(mockCtrl)
			startCall = mockRegistryServerManager.EXPECT().Start("fake-username", "fake-password", "fake-host", 123).Return(mockRegistryServer, nil)
			spyCall = spy.EXPECT().Record()
			stopCall = mockRegistryServer.EXPECT().Stop().Return(nil)

			logBuffer = gbytes.NewBuffer()
			goLogger := log.New(logBuffer, "", log.LstdFlags)
			logger = boshlog.New(boshlog.LevelWarn, goLogger, goLogger)
			fakeStage = fakebiui.NewFakeStage()
		})

		It("starts the registry before calling the function", func() {
			spyCall.After(startCall)

			err := newInstalation().WithRunningRegistry(logger, fakeStage, func() error {
				spy.Record()
				return nil
			})
			Expect(err).NotTo(HaveOccurred())
		})

		It("performs stages for starting and stopping the registry", func() {
			err := newInstalation().WithRunningRegistry(logger, fakeStage, func() error {