package aggregate

import (
	"github.com/pingcap-inc/clinic/pkg/ngm/statements/api"
	"github.com/pingcap-inc/clinic/pkg/ngm/statements/load"
)

func AggAvgCompileLatency() Aggregator {
	return &AvgCompileLatency{}
}

type AvgCompileLatency struct {
	sum int64
	cnt int64
}

var _ Aggregator = (*AvgCompileLatency)(nil)

func (a *AvgCompileLatency) Add(record *load.StmtRecord) {
	a.sum += int64(record.SumCompileLatency)
	a.cnt += record.ExecCount
}

func (a *AvgCompileLatency) Merge(agg Aggregator) {
	if agg, ok := agg.(*AvgCompileLatency); ok {
		a.sum += agg.sum
		a.cnt += agg.cnt
	}
}

func (a *AvgCompileLatency) Output(model *api.Model) {
	if a.cnt > 0 {
		model.AvgCompileLatency = int(a.sum / a.cnt)
	}
}
