package qihoo360testcase

import (
	"fmt"
	"time"

	"github.com/pingcap/test-infra/caselib/pkg/model/ticdc"
	"github.com/pingcap/test-infra/caselib/pkg/model/workload"
	"github.com/pingcap/test-infra/caselib/pkg/steps"
	"github.com/pingcap/test-infra/caselib/ticdc/common"
	"github.com/pingcap/tiflow/cdc/model"
)

// CdcLargeNumberChangefeed
// Init CDC Components: tidb cluster / sink (mysql)
// Create amount of changefeeds with config filter, each changefeed sync one sysbench table
// Init and run workload: sysbench
// Wait workload finish: even though workload finished, but it does not mean changefeed has synced all data
// Check consistency.

func Qihoo360LargeNumberChangefeed() steps.Step {
	var (
		loopLifeTime                = time.Hour
		loopCron                    = 1 * time.Second
		changeFeedPrefix            = "cdc-large-number-changefeed-"
		changefeedCategory          = `[filter]`
		changefeeCount              = 300
		dbName360                   = common.DBName
		createChangefeedsWithConfig []steps.Step
		removeChangefeed            []steps.Step
		changefeedContentFinishmark = fmt.Sprintf(`rules = ['%s.finishmark']`, common.DBName)
	)
	for i := 0; i <= changefeeCount; i++ {
		tableName := fmt.Sprintf("sbtest%d", i)
		changeFeedName := fmt.Sprintf("%s%d", changeFeedPrefix, i)
		changefeedContent := fmt.Sprintf(`rules = ['%s.%s']`, common.DBName, tableName)

		createChangefeedsWithConfig = append(createChangefeedsWithConfig, steps.NewChangeFeedConfig(&changefeedCategory, &changefeedContent))
		createChangefeedsWithConfig = append(createChangefeedsWithConfig, steps.NewChangeFeedTask(&ticdc.ChangeFeedCreateFlags{SinkType: ticdc.SinkTypeMySQL, ID: changeFeedName, Config: true}))

		removeChangefeed = append(removeChangefeed, steps.NewChangeFeedTask(&ticdc.ChangeFeedAdminJobFlags{JobType: model.AdminRemove, ID: changeFeedName, ForceRemove: true}))
	}
	return steps.
		NewBuilder().
		LoadEnv().
		LoadResourceFromEnv("TI_PARAM_RES_upstream", common.ResourceHandleSource).
		LoadResourceFromEnv("TI_PARAM_RES_downstream", common.ResourceHandleMySQL).
		LoadResourceFromEnv("TI_PARAM_RES_workload", common.ResourceHandleWorkload).
		InitCDCComponents(common.ResourceHandleSource, common.ResourceHandleMySQL).
		InitChangefeedConfig(&changefeedCategory, &changefeedContentFinishmark).
		OperateChangeFeed(&ticdc.ChangeFeedCreateFlags{SinkType: ticdc.SinkTypeMySQL, ID: "finishmark-task", Config: true}).
		RunLoopTask(loopLifeTime, loopCron, false, createChangefeedsWithConfig...).
		CreateDatabase(common.ResourceHandleSource, common.DBName).
		InitWorkload(common.ResourceHandleWorkload).
		RunWorkload(&workload.QihooOption{
			Command:        workload.CommandTypeLoad,
			PropertyFile:   "./workloads/oncall2929", // property file is located inside 360 workload image
			PropertyValues: []string{"operationcount=50000", "autocommit=1", "databasename=" + common.DBName, "tablecount=10"},
			Threads:        20,
			Duration:       3 * time.Hour, // we do not know how long the command will take, set it to 8 at the moment.
		}).
		RunWorkload(&workload.QihooOption{
			Command:        workload.CommandTypeRun,
			PropertyFile:   "./workloads/oncall2929", // property file is located inside 360 workload image
			PropertyValues: []string{"operationcount=10000", "autocommit=1", "databasename=" + common.DBName, "tablecount=10", "exectime=3600"},
			Threads:        20,
			Duration:       2 * time.Hour, // we do not know how long the command will take, set it to 24 at the moment.
		}).
		SendFinishMark(common.DBName).
		WaitFinishMark(common.ResourceHandleMySQL, common.DBName, 40*time.Minute).
		CheckConsistency(common.ResourceHandleSource, common.ResourceHandleMySQL, common.DBName).
		DropDatabasesIfExists(common.ResourceHandleSource, &dbName360).
		Sleep(1*time.Minute).
		RunLoopTask(loopLifeTime, loopCron, false, removeChangefeed...).
		Build()
}
