package main

import (
	"sort"
	"time"
)

func (t timespan) coverage(ts ...timespan) time.Duration {
	if len(ts) == 0 {
		return 0
	}

	starts := append([]timespan(nil), ts...)
	sort.Sort(timespans(starts))

	a := starts[0].Start()
	b := a
	var d time.Duration

	for i := 0; i < len(starts); i++ {
		span := starts[i]

		if span.Start().After(b) {
			// keep score before skipping over empty section
			if a.Before(t.Start()) {
				a = t.Start()
			}
			if b.After(t.End()) {
				b = t.End()
			}
			if a.Before(t.End()) && b.After(t.Start()) {
				d += b.Sub(a)
			}
			a, b = span.Start(), span.End()
		}
		if span.End().After(b) {
			// claim territory
			b = span.End()
		}
	}

	// score the last range we encountered
	if a.Before(t.Start()) {
		a = t.Start()
	}
	if b.After(t.End()) {
		b = t.End()
	}
	if a.Before(t.End()) && b.After(t.Start()) {
		d += b.Sub(a)
	}

	return d
}
