package profiling

import (
	"context"
	"io"
	"time"

	. "github.com/onsi/gomega"
	. "github.com/pingcap/endless/pkg/util"
	"github.com/pingcap/endless/testcase/oltp/oltppkg"
	"github.com/pingcap/log"
	"github.com/pingcap/test-infra/sdk/resource"
	"golang.org/x/sync/errgroup"
)

func OLTP_PROFILING_STABILITY(
	ctx context.Context,
	tc resource.TiDBCluster,
	pr *io.PipeReader,
	caseCmdParms oltppkg.CaseCmdParms,
) {
	var runTime time.Duration
	if caseCmdParms.RunTime.TotalRunTime != 0 {
		runTime = caseCmdParms.RunTime.TotalRunTime
	} else {
		runTime = 2 * time.Hour
	}
	ctxAll, cancel := context.WithTimeout(ctx, runTime)
	defer cancel()
	g, gctx := errgroup.WithContext(ctxAll)

	oltppkg.FunCommonCheck(gctx, tc, g, runTime, pr)

	g.Go(WithGinkgoRecover(func() {
		for {
			select {
			case <-gctx.Done():
				log.Info("ctx done.")
				return
			default:
			}
			log.Info("start profiling.")
			err := AllTiKVProfiling(tc, "profile", "30")
			Expect(err).Should(Succeed())
			err = PDProfiling(tc, "zip", "30")
			Expect(err).Should(Succeed())
		}
	}))
	Expect(g.Wait()).Should(BeNil())
}
