package testcase

import (
	"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"
)

// QihooSync run 360 workload
// create tidb cluster / mysql / workload
// create changefeed
// run 360 workload
// wait for workload finish
// check consistency
var _ = common.AddTestCase("qihoo_360_sync", func() steps.Step {
	var (
		dbNameVar    = common.DBName
		changefeedID = "qihoo360-sync-task"
	)
	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).
		OperateChangeFeed(&ticdc.ChangeFeedCreateFlags{
			SinkType: ticdc.SinkTypeMySQL,
			ID:       changefeedID,
		}).
		CreateDatabase(common.ResourceHandleSource, dbNameVar).
		Sleep(20*time.Second).
		OperateChangeFeed(&ticdc.ChangeFeedAdminJobFlags{
			JobType: model.AdminStop,
			ID:      changefeedID,
		}).
		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=" + dbNameVar, "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.
		}).
		OperateChangeFeed(&ticdc.ChangeFeedAdminJobFlags{
			JobType: model.AdminResume,
			ID:      changefeedID,
		}).
		Parallel(
			steps.NewRunWorkload(&workload.QihooOption{
				Command:        workload.CommandTypeRun,
				PropertyFile:   "./workloads/oncall2929", // property file is located inside 360 workload image
				PropertyValues: []string{"operationcount=10000", "autocommit=1", "databasename=" + dbNameVar, "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(dbNameVar).
		WaitFinishMark(common.ResourceHandleMySQL, dbNameVar, 5*time.Hour).
		CheckConsistency(common.ResourceHandleSource, common.ResourceHandleMySQL, dbNameVar).
		DropDatabasesIfExists(common.ResourceHandleSource, &dbNameVar).
		Sleep(1 * time.Minute).
		OperateChangeFeed(&ticdc.ChangeFeedAdminJobFlags{JobType: model.AdminRemove, ID: changefeedID, ForceRemove: true}).
		Build()
})
