package common

import (
	"context"
	"github.com/pingcap/errors"
	"go.uber.org/zap"
	"math"
	"time"

	l4g "github.com/alecthomas/log4go"
	pkg2 "github.com/pingcap/endless/testcase/tiflash/pkg"
	"github.com/stretchr/testify/assert"
)

func TiProxyConnectionBalanceChecker(ctx context.Context, t assert.TestingT, provider, clusterId string) error {
	judgeTiDBUptimeMoreThanTwoMinutes := func(t assert.TestingT, provider, clusterId string) (bool, error) {
		tidbUpTime, err := GetTiDBUptime(t, provider, clusterId)
		if err != nil {
			return false, err
		}
		for instance, v := range tidbUpTime {
			if v[0] < 120 {
				l4g.Warn("tidb instance uptime less than 2 minutes [instance=%v] [uptime=%v]", instance, v[0])
				return false, nil
			}
		}
		return true, nil
	}

	for {
		pkg2.Sleep(ctx, 10*time.Second)
		select {
		case <-ctx.Done():
			l4g.Info("TiProxy connect balance checker end for ctx done")
			return nil
		default:
		}
		// TiProxy will balance connection in 2 minutes after TiDB up
		if flag, err := judgeTiDBUptimeMoreThanTwoMinutes(t, provider, clusterId); err != nil {
			return err
		} else if !flag {
			continue
		}
		activeConnection, err := GetConnection(t, provider, clusterId)
		if err != nil {
			return err
		}
		for instance1, connection1 := range activeConnection {
			l4g.Info("tidb-server active connection [instance=%v] [connection=%v]", instance1, connection1)
			for instance2, connection2 := range activeConnection {
				if instance1 == instance2 {
					continue
				}
				l4g.Info("tidb-server active connection [instance=%v] [connection=%v]", instance2, connection2)
				for i := 0; i < len(connection1); i++ {
					for j := 0; j < len(connection2); j++ {
						count1, count2 := float64(connection1[i]), float64(connection2[j])
						diff := math.Abs((count1 - count2) / count2)
						if diff > 0.40 {
							l4g.Error("tidb-server connection count diff more than 40%", zap.Float64("count1", count1), zap.Float64("count2", count2), zap.Float64("diff", diff))
							return errors.New("tidb connector count more than 40% when TiProxy deploy, connect count")
						}
					}
				}
			}
		}
	}

}
