package cmd

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"os"

	"github.com/golang/mock/gomock"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/jenkins-zh/jenkins-cli/client"
	"github.com/jenkins-zh/jenkins-cli/mock/mhttp"
)

var _ = Describe("center watch command", func() {
	var (
		ctrl         *gomock.Controller
		roundTripper *mhttp.MockRoundTripper
	)

	BeforeEach(func() {
		ctrl = gomock.NewController(GinkgoT())
		roundTripper = mhttp.NewMockRoundTripper(ctrl)
		rootCmd.SetArgs([]string{})
		rootOptions.Jenkins = ""
		rootOptions.ConfigFile = "test.yaml"

		centerWatchOption.WatchOption.Count = -1
		centerWatchOption.RoundTripper = roundTripper
		centerOption.RoundTripper = roundTripper
	})

	AfterEach(func() {
		rootCmd.SetArgs([]string{})
		os.Remove(rootOptions.ConfigFile)
		rootOptions.ConfigFile = ""
		ctrl.Finish()
	})

	Context("basic cases", func() {
		It("should success, center watch command", func() {
			data, err := GenerateSampleConfig()
			Expect(err).To(BeNil())
			err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
			Expect(err).To(BeNil())

			requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/api/json", nil)
			requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
			responseCrumb := &http.Response{
				StatusCode: 200,
				Proto:      "HTTP/1.1",
				Request:    requestCrumb,
				Body: ioutil.NopCloser(bytes.NewBufferString(`
				{"version":"0"}
				`)),
			}
			roundTripper.EXPECT().
				RoundTrip(client.NewRequestMatcher(requestCrumb)).Return(responseCrumb, nil)

			rootCmd.SetArgs([]string{"center", "watch"})
			_, err = rootCmd.ExecuteC()
			Expect(err).To(BeNil())
		})

		It("allPluginsCompleted", func() {
			Expect(allPluginsCompleted(nil)).To(Equal(false))

			status := &client.UpdateCenter{}
			Expect(allPluginsCompleted(status)).To(Equal(false))

			// all install job is completed
			status.Jobs = []client.InstallationJob{{
				UpdateCenterJob: client.UpdateCenterJob{Type: "InstallationJob"},
				Status: client.InstallationJobStatus{
					Success: true,
				},
			}}
			Expect(allPluginsCompleted(status)).To(Equal(true))

			// there's one install job is not completed
			status.Jobs = append(status.Jobs, client.InstallationJob{
				UpdateCenterJob: client.UpdateCenterJob{Type: "InstallationJob"},
				Status: client.InstallationJobStatus{
					Success: false,
				},
			})
			Expect(allPluginsCompleted(status)).To(Equal(false))
		})
	})
})
