package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/pingcap/schrodinger-test/util"
	client "github.com/pingcap/schrodinger/pkg/test_client"
)

var (
	dbName          string
	dbcount         int
	tablecount      int
	tableBatchCount int
	maxTime         int
	transaction     bool
	runMode         string
)

func init() {
	flag.StringVar(&dbName, "db", "db_lt", "database name")
	flag.IntVar(&dbcount, "db-count", 1, "number of dbs")
	flag.IntVar(&tablecount, "table-count", 10000, "number of tables pre db")
	flag.IntVar(&tableBatchCount, "batch-count", 100, "The number of tables in a batch")
	flag.IntVar(&maxTime, "max-time", 1000, "Creating a single table takes the most time,ms")
	flag.BoolVar(&transaction, "transaction", false, "Use transactions per batch,default value: false ,not use")
	flag.StringVar(&runMode, "run-mode", "online", "case mode, support values: online / dev, default value: online")
}

func main() {
	client.Info("[bench_largetables] start...")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	cli := client.New(ctx, func(mode string) (clientMode client.Mode) {
		switch client.Mode(mode) {
		case client.ModeOnline:
			clientMode = client.ModeOnline
		case client.ModeDev:
			clientMode = client.ModeDev
		default:
			client.Fatalf("[bench_largetables] Invalid mode: %v,support values: online / dev", mode)
		}
		client.Info("Mode:", clientMode)
		return clientMode
	}(runMode))

	dbAddr := cli.TiDBService()
	dbDSN := fmt.Sprintf("root:@tcp(%s)/%s", dbAddr, "mysql")
	db, err := util.OpenDB(dbDSN, 1)
	if err != nil {
		client.Fatalf("[bench_largetables] create db client error %v", err)
	}

	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)
	go func() {
		sig := <-sc
		client.Infof("Got signal [%d] to exist", sig)
		cancel()
		os.Exit(0)
	}()

	largeTables := &LargeTables{
		DbName:          dbName,
		DbCount:         dbcount,
		TableCount:      tablecount,
		TableBatchCount: tableBatchCount,
		MaxTime:         maxTime,
		Transaction:     transaction,
	}

	client.Infof("[bench_largetables] config:%v", largeTables)
	client.Infof("[bench_largetables] start to run")
	testResult, err := largeTables.run(cli, db)
	if err != nil {
		client.Errorf("[bench_largetables] exec run failed: %v", err)
	}

	client.Infof("[bench_largetables] bench_largetables result: %v", testResult)
	if err := cli.ReportTestResult(testResult); err != nil {
		client.Errorf("[bench_largetables] report case result %v, failed: %v", testResult, err)
	}

	client.Infof("[bench_largetables] end...")
}
