package qihoo360testcase

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/test-infra/sdk/resource"
	"github.com/pingcap/tiflow/cdc/model"
)

// CdcTikvRegionSplitSync
// create tidb cluster / mysql / workload
// create changefeed
// create database
// run workload
// modify region/key size to let region split
// finish mark synced to downstream.
// wait for workload finish
// check consistency

func Qihoo360TikvRegionSplitSync() steps.Step {
	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.ChangeFeedAdminJobFlags{JobType: model.AdminStop, ID: common.ChangefeedMySQL360}).
		InitWorkload(common.ResourceHandleWorkload).
		RunWorkload(&workload.QihooOption{
			Command:        workload.CommandTypeRun,
			PropertyFile:   "./workloads/oncall2929", // property file is located inside 360 workload image
			PropertyValues: []string{"operationcount=50000", "autocommit=1", "databasename=" + common.DBName, "tablecount=200", "exectime=3600"},
			Threads:        200,
			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: common.ChangefeedMySQL360}).
		Parallel(

			steps.NewUpdateConfig(resource.TiKV, "[coprocessor]\nregion-max-size = \"72MB\"\nregion-split-size = \"48MB\"\nregion-max-keys = 720000\nregion-split-keys = 480000", 10*time.Minute),

			steps.NewRunWorkload(&workload.QihooOption{
				Command:        workload.CommandTypeRun,
				PropertyFile:   "./workloads/oncall2929", // property file is located inside 360 workload image
				PropertyValues: []string{"operationcount=5000000", "autocommit=1", "databasename=" + common.DBName, "tablecount=200", "exectime=3600"},
				Threads:        200,
				Duration:       2 * time.Hour, // we do not know how long the command will take, set it to 24 at the moment.
			}),
		).
		// UpdateConfig(resource.PD, "[schedule]\nmax-merge-region-keys = 20\nmax-merge-region-size = \"2MB\"", 10 * time.Minute).
		SendFinishMark(common.DBName).
		WaitFinishMark(common.ResourceHandleMySQL, common.DBName, 2*time.Hour).
		CheckConsistency(common.ResourceHandleSource, common.ResourceHandleMySQL, common.DBName).
		Build()
}
