package otherutils

import (
	"leafstalk/log"
	"time"
)

type HitCount struct {
	count int
	tick  int64
	isAcc bool
	name  string
}

func NewHitCount(name string, isAcc bool) *HitCount {
	hc := new(HitCount)
	hc.name = name
	hc.isAcc = isAcc
	return hc
}

// 统计调用次数或每秒调用次数
// 1000000
func (h *HitCount) Hit() {
	h.count += 1
	if h.count%300 == 0 {
		ct := time.Now().Unix()
		if ct-h.tick >= 5 {
			if h.isAcc {
				log.Warnf("%s receivePacket Count %v", h.name, h.count)
			} else {
				log.Warnf("%s receivePacket Count %v", h.name, h.count/5)
				h.count = 0
			}
			h.tick = ct
		}
	}
}

// 按指定频率调用callBack，
func StartTicker(d time.Duration, name string, rate int, callBack func()) {
	stopTimer := time.NewTimer(d)
	logTicker := time.NewTicker(time.Second * 2)

	// 1s = 20*50MS
	sendTicker := time.NewTicker(time.Millisecond * 50)
	rate = (rate + 19) / 20

	go func() {

		wt := time.NewTimer(5 * time.Second)
		<-wt.C

		ncount := 0
		for {
			select {
			case <-stopTimer.C:
				logTicker.Stop()
				log.Warnf("%s sendPacket End: %v", name, ncount)
				return
			case <-logTicker.C:
				log.Warnf("%s sendPacket Count: %v", name, ncount/2)
				ncount = 0
				continue
			case <-sendTicker.C:
				for i := 0; i < rate; i += 1 {
					callBack()
					ncount += 1
				}
			}
		}
	}()
}
