// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package testcases

import (
	"github.com/pingcap/test-infra/caselib/pkg/model/workload"
	"github.com/pingcap/test-infra/caselib/pkg/spec"
	"github.com/pingcap/test-infra/caselib/pkg/steps"
	"github.com/pingcap/test-infra/caselib/pkg/utils"
	_ "github.com/pingcap/test-infra/sdk/resource/impl/k8s"
)

func init() {
	var (
		taskName       = "test-infra"
		sourceName0    = "source-0"
		sourceNameList = []string{sourceName0}
		name           = "dm_benchbot_1g_binlog_file"
		boundWorker0   = new(string)
		duration       = new(string)
		version        = new(string)
		hashCode       = new(string)
		executeSql     = new(string)
		dsn            string
		env            = newCommonEnv()
	)
	var _ = AddTestCase(spec.CaseName(name), func() steps.Step {
		// env.cleanUpEnv(name)
		env.init().b.
			LoadParamFromEnv(utils.ParamPrefix+"dsn", &dsn).
			CreateDatabase(env.UpStreams[0], name).
			DmRunWorkload(env.UpStreams[0], env.Dm, env.Workload, Spec.GetWorkloadOption(workload.CommandTypePrepare)).
			DmCreateSources(env.Dm, env.DmHost, Path.SourcePaths).
			DmStartTasks(env.Dm, env.DmHost, Path.TaskPaths).
			DmWaitTaskSynced(env.DmHost, taskName, sourceNameList).
			DmPauseTask(env.Dm, env.DmHost, Path.TaskPaths[0]).
			DmRunWorkload(env.UpStreams[0], env.Dm, env.Workload, Spec.GetWorkloadOption(workload.CommandTypeRun)).
			DmResumeTask(env.Dm, env.DmHost, Path.TaskPaths[0]).
			DmWaitTaskSynced(env.DmHost, taskName, sourceNameList).
			// Get bounded worker
			DmGetSourceWorker(env.DmHost, sourceName0, boundWorker0).
			// Get the binlog event, and count the cost
			Count1GBinlogConsumeDuration(env.DmHost, boundWorker0, duration).
			GetDMWorkerVersion(env.DmHost, boundWorker0, version, hashCode).
			// Generate sql statement
			// workloadId is 1 (sysbench)
			// benchMarktype is 1 (1GB Binlog File Consume Duration)
			// version is got from GetDMWorkerVersion
			// hashCode is got from GetDMWorkerVersion
			// gtidStatus is 1 (opened)
			// relayStatus is 0 (closed)
			// tableSharding is 0 (closed)
			// duration is got from Count1GBinlogConsumeDuration
			// time is NOW()
			Generate1GBinlogConsumeDurationSql("1", "1", version, hashCode, "1", "0", "0", duration, executeSql).
			// Upload result
			ExecuteSqlOnPulibcDatabase(&dsn, executeSql)
		return env.toBuilder().Build()
	})
}
