package main

import (
	"fmt"
	"time"
)

type sortDuration []time.Duration

func (s sortDuration) Len() int {
	return len(s)
}

func (s sortDuration) Less(i, j int) bool {
	return s[i] < s[j]
}

func (s sortDuration) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func percentile(sorted []time.Duration, fraction float64) (time.Duration, error) {
	if fraction < 0 || fraction > 1 {
		return 0, fmt.Errorf("fraction domain is [0,1]")
	}

	l := len(sorted)
	if l == 0 {
		return 0, fmt.Errorf("not defined for zero-length input sets")
	}

	idx := float64(l-1) * fraction
	// TODO: index rounding, tie-break averaging
	iidx := int(idx)
	if iidx < 0 {
		iidx = 0
	}
	if iidx > l-1 {
		iidx = l - 1
	}
	return sorted[iidx], nil
}
