package workload

import (
	"context"
	"database/sql"
	"fmt"
	"net/url"
	"strconv"

	"github.com/pingcap/endless/pkg/client/tidb"
	"github.com/pingcap/endless/pkg/matcher"
	"github.com/pingcap/endless/pkg/workloadnode"
	"github.com/pingcap/log"
	"github.com/pingcap/test-infra/sdk/core"
	"github.com/pingcap/test-infra/sdk/resource"
	"go.uber.org/zap"
)

type SysbenchWorkLoad struct {
	ctx            core.TestContext
	tc             resource.TiDBCluster
	dbName         string
	tables         int
	tableSize      int
	dbUrl          *url.URL
	time           int
	threads        int
	secondaryIndex bool
	wlNode         resource.WorkloadNode
}

func NewWorkload(ctx core.TestContext, dbName string) *SysbenchWorkLoad {
	tablesize := matcher.Try(strconv.Atoi(ctx.Param("table_size", "1000000"))).(int)
	tables := matcher.Try(strconv.Atoi(ctx.Param("table_size", "10"))).(int)
	threads := matcher.Try(strconv.Atoi(ctx.Param("threads", "10"))).(int)

	tc := ctx.Resource("tc").(resource.TiDBCluster)
	wlNode := ctx.Resource("sysbenchnode").(resource.WorkloadNode)

	dbUrl, _ := tc.ServiceURL(resource.DBAddr)

	return &SysbenchWorkLoad{
		ctx:            ctx,
		tc:             tc,
		dbName:         dbName,
		tables:         tables,
		tableSize:      tablesize,
		dbUrl:          dbUrl,
		time:           600,
		threads:        threads,
		secondaryIndex: false,
		wlNode:         wlNode}

}

func (sw *SysbenchWorkLoad) Prepare(ctx context.Context) {
	cli := tidb.NewClient(matcher.Try(sw.tc.GetDB("")).(*sql.DB))
	if _, err := cli.Exec(fmt.Sprintf("create database if not exists %s", sw.dbName)); err != nil {
		log.Error("failed to create database for sysbench", zap.Error(err))
		return
	}
	//
	// mysql-host=tidb.32ec3106.7604b7d0.ap-south-1.shared.aws.tidbcloud.com
	// mysql-port=4000
	// mysql-user=root
	// mysql-db=sbtest
	// time=600
	// threads=10
	// report-interval=10
	// db-driver=mysql
	prepareCmd := fmt.Sprintf("sysbench oltp_common --mysql-host=%s --mysql-port=%s --mysql-user=root --mysql-db=%s --time=%d --threads=%d --report-interval=10 --db-driver=mysql --tables=%d --table-size=%d --create_secondary=%t prepare", sw.dbUrl.Hostname(), sw.dbUrl.Port(), sw.dbName, sw.time, sw.threads, sw.tables, sw.tableSize, sw.secondaryIndex)
	log.Info("start to prepare the date", zap.String("prepare_cmd", prepareCmd))
	cmd := workloadnode.CommandContext(ctx, prepareCmd)
	defer cmd.Stop()
	cmd.Run(sw.wlNode)
}
