package tidbcluster

import (
	"context"
	"fmt"
	"time"

	"github.com/golang/mock/gomock"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pingcap/test-infra/sdk/resource"

	mockm "github.com/pingcap/endless/pkg/matcher/metrics/generated"
	"github.com/pingcap/endless/pkg/util"
	"github.com/pingcap/endless/pkg/util/schedule"
)

func GetReplicas(o resource.TiDBClusterScaleOptions) uint32 {
	fmt.Printf("Replicas: %d\n", o.Replicas)
	return o.Replicas
}

var _ = Describe("TiDBClusterOperations", func() {
	Context("RandomScale", func() {
		var MockTc *mockm.MockTiDBCluster
		var TiDBClusterScaleOpts chan resource.TiDBClusterScaleOptions
		Schedule := "@every 100ms"
		ContextTimeout := 200 * time.Millisecond

		BeforeEach(func() {
			TiDBClusterScaleOpts = make(chan resource.TiDBClusterScaleOptions)
			MockTc = mockm.NewMockTiDBCluster(GomockController)
			MockTc.EXPECT().Scale(gomock.Any()).DoAndReturn(func(opts resource.TiDBClusterScaleOptions) error {
				TiDBClusterScaleOpts <- opts
				return nil
			}).AnyTimes()
		})
		AfterEach(func() {
			close(TiDBClusterScaleOpts)
		})

		It("works fine", util.Repeat(3, func() {
			ctx, cancel := context.WithTimeout(context.TODO(), ContextTimeout)
			defer cancel()
			op := RandomScale(MockTc, resource.TiDB, 2, 5, 5*time.Minute)
			err := schedule.RunPeriodically(ctx, Schedule, 100*time.Millisecond, op, "testTiDBRandomScale")
			Expect(err).ShouldNot(HaveOccurred())
			Eventually(TiDBClusterScaleOpts).Should(Receive(
				WithTransform(GetReplicas,
					SatisfyAll(
						BeNumerically(">=", 2),
						BeNumerically("<=", 5),
					))))
		}))
	})
})
