package main

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

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

var (
	concurrency = flag.Int("concurrency", 200, "concurrency of sql.DB. default: 200")
	recordCount = flag.Int("record", 10000, "amount of records, size of each record is 1kB. default: 10000")
	workerCount = flag.Int("worker", 300, "threads to execute random job. default: 300")
)

func main() {
	client.Info("[hotspot] Start...")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	cli := client.New(ctx, client.ModeOnline)

	dbDSN := fmt.Sprintf("root:@tcp(%s)/%s", cli.TiDBService(), "test")
	db, err := util.OpenDB(dbDSN, *concurrency)
	if err != nil {
		client.Fatalf("[hotspot] Opening database failed: %v", errors.Trace(err))
	}
	defer db.Close()

	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	go func() {
		sig := <-sc
		client.Infof("[hotspot] Got signal [%s] to exit.", sig)
		cancel()
	}()

	test := NewHotspotTest(cli, db, *recordCount, *workerCount)
	err = test.Init()
	if err != nil {
		client.Fatalf("[hotspot] Initializing test failed: %v", errors.Trace(err))
	} else {
		client.Info("[hotspot] Initializing success")
	}
	test.Run(ctx)
}
