package stat

import (
	"encoding/json"
	"fmt"
	"time"
)

// How many values we store to calculate average time
const avgCount = 10

// AvgTime Structure for average time calculations
type AvgTime struct {
	Value    time.Duration `json:"value"`
	index    uint64
	duration [avgCount]time.Duration
}

// Add time
func (stat *AvgTime) Add(d time.Duration) {

	if stat.index%avgCount == 0 {
		stat.Value = 0
		for _, cur := range stat.duration {
			stat.Value += cur
		}

		stat.Value = stat.Value / avgCount
	}

	stat.duration[stat.index%avgCount] = d
	stat.index++
}

// AddStat sum current average time with other
func (stat *AvgTime) AddStat(newStat *AvgTime) {
	for _, cur := range newStat.duration {
		stat.Add(cur)
	}
}

func (stat AvgTime) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Value string `json:"value"`
	}{
		Value: fmt.Sprintf("%v", stat.Value),
	})
}

func (stat AvgTime) String() string {
	bytes, err := json.Marshal(stat)
	if err != nil {
		return fmt.Sprintf("Can't serialize: %v", err)
	}

	return string(bytes)
}
