package aggregate

import (
	"math"

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

func AggMaxLatency() Aggregator {
	return &MaxLatency{math.MinInt64}
}

type MaxLatency struct {
	max int64
}

var _ Aggregator = (*MaxLatency)(nil)

func (a *MaxLatency) Add(record *load.StmtRecord) {
	if record.MaxLatency.Nanoseconds() > a.max {
		a.max = record.MaxLatency.Nanoseconds()
	}
}

func (a *MaxLatency) Merge(agg Aggregator) {
	if agg, ok := agg.(*MaxLatency); ok {
		if agg.max > a.max {
			a.max = agg.max
		}
	}
}

func (a *MaxLatency) Output(model *api.Model) {
	model.MaxLatency = int(a.max)
}
