package main

import (
	"bytes"
	"encoding/binary"
	"math"
	"sort"
	"strings"
	"syscall"
	"testing"
	"time"
)

func secs(s float64) time.Duration { return time.Duration(s * float64(time.Second)) }

var (
	ok     = ending{}
	killed = ending{sig: syscall.SIGTERM}
)

func TestStrokeCount(t *testing.T) {
	for _, c := range []struct {
		e    ending
		s    float64
		want int
	}{
		{ok, 4, 9}, {ok, 59.9, 9}, {ok, 60, 10}, {ok, 125, 11}, {ok, 3600, 69}, {ok, 7200, 69},
		{killed, 10, 3}, {killed, 180, 6},
	} {
		p, m := strokeCount(c.e, secs(c.s))
		if p+m != c.want {
			t.Errorf("%v at %v s: %d strokes, want %d", c.e, c.s, p+m, c.want)
		}
	}
}

func TestLength(t *testing.T) {
	for _, c := range []struct {
		prelude, minutes int
		want             float64
	}{{9, 0, 4.8}, {9, 1, 5.6}, {9, 60, 29.2}, {3, 0, 2.4}, {3, 3, 4.0}} {
		got := float64(len(peal(c.prelude, c.minutes, false))) / rate
		if math.Abs(got-c.want) > 1e-9 {
			t.Errorf("peal %d+%d: %v s, want %v s", c.prelude, c.minutes, got, c.want)
		}
	}
	p, m := strokeCount(ok, secs(3600))
	if got := float64(len(peal(p, m, true))) / rate; got >= 30 {
		t.Errorf("the peal of a one hour command is %v s, not under 30 s", got)
	}
}

// icmt reads the comment back out of an encoded peal.
func icmt(b []byte) string {
	i := bytes.Index(b, []byte("ICMT"))
	n := int(binary.LittleEndian.Uint32(b[i+4:]))
	return strings.TrimRight(string(b[i+8:i+8+n]), "\x00")
}

func TestRecord(t *testing.T) {
	for _, c := range []struct {
		e    ending
		s    float64
		want string
	}{
		{ok, 59.9, "tailors: 59 s, exit 0, 9 strokes."},
		{ok, 60, "tailors: 1 min 0 s, exit 0, 10 strokes."},
		{ending{code: 1}, 252, "tailors: 4 min 12 s, exit 1, 13 strokes."},
		{ok, 3600, "tailors: 1 h 0 min, exit 0, 69 strokes."},
		{ending{sig: syscall.SIGINT}, 1.2, "tailors: 1 s, killed by SIGINT, 3 strokes."},
		{ending{sig: 33}, 5, "tailors: 5 s, killed by signal 33, 3 strokes."},
	} {
		p, m := strokeCount(c.e, secs(c.s))
		line := record(c.e, secs(c.s), p+m, plain) + "."
		if line != c.want {
			t.Errorf("record line %q, want %q", line, c.want)
		}
		b := wav(peal(p, m, c.e.failed()), record(c.e, secs(c.s), p+m, plain))
		if got := icmt(b); got != strings.TrimSuffix(c.want, ".") {
			t.Errorf("ICMT %q, want %q", got, strings.TrimSuffix(c.want, "."))
		}
	}
	if got := record(ending{code: 2}, secs(1), 9, brick); got != "tailors: 1 s, exit \x1b[38;2;236;94;82m2\x1b[39m, 9 strokes" {
		t.Errorf("painted record %q", got)
	}
}

// goertzel gives the power of x at hz.
func goertzel(x []float64, hz float64) float64 {
	c := 2 * math.Cos(2*math.Pi*hz/rate)
	var s1, s2 float64
	for _, v := range x {
		s1, s2 = v+c*s1-s2, s1
	}
	return s1*s1 + s2*s2 - c*s1*s2
}

// strongest scans 50 Hz to 1 kHz by 1 Hz, then the best bin by 0.01 Hz.
func strongest(x []float64) float64 {
	best, at := 0.0, 0.0
	scan := func(lo, hi, step float64) {
		for f := lo; f <= hi; f += step {
			if p := goertzel(x, f); p > best {
				best, at = p, f
			}
		}
	}
	scan(50, 1000, 1)
	scan(at-1, at+1, 0.01)
	return at
}

func TestFlatStroke(t *testing.T) {
	normal, flatS := stroke(1), stroke(flat)
	n, f := strongest(normal), strongest(flatS)
	if r := f / n; math.Abs(r/0.94387-1) > 0.002 {
		t.Errorf("flat strongest %.2f Hz, normal %.2f Hz, ratio %.5f, want 0.94387", f, n, r)
	}
	if math.Abs(n/f0-1) > 0.002 {
		t.Errorf("normal strongest %.2f Hz, want %.2f Hz", n, f0)
	}
	off, on := goertzel(flatS, f0), goertzel(flatS, f0*flat)
	if on < 1000*off {
		t.Errorf("flat stroke: %.3g at 246.9 Hz is not 1000 times %.3g at 261.63 Hz", on, off)
	}
	t.Logf("strongest partial: normal %.2f Hz, flat %.2f Hz, ratio %.5f; flat stroke energy 246.9 Hz / 261.63 Hz = %.0f",
		n, f, f/n, on/off)
}

func TestFlatOnlyMovesLastStroke(t *testing.T) {
	for _, c := range [][2]int{{9, 0}, {3, 0}, {9, 60}} {
		at := strikes(c[0], c[1])
		last := at[len(at)-1]
		a, b := peal(c[0], c[1], true), peal(c[0], c[1], false)
		for i := 0; i < last; i++ {
			if a[i] != b[i] {
				t.Fatalf("%d strokes: sample %d differs before the last strike at %d", len(at), i, last)
			}
		}
		if bytes.Equal(wav(a, ""), wav(b, "")) {
			t.Errorf("%d strokes: flat and normal peals are identical", len(at))
		}
	}
}

func TestDeterministic(t *testing.T) {
	a := wav(peal(9, 60, true), "x")
	b := wav(peal(9, 60, true), "x")
	if !bytes.Equal(a, b) {
		t.Error("the same inputs gave different bytes")
	}
}

func TestStrokeEnd(t *testing.T) {
	for _, pitch := range []float64{1, flat} {
		s := stroke(pitch)
		if s[len(s)-1] != 0 {
			t.Errorf("pitch %v: last sample %v, want exactly 0", pitch, s[len(s)-1])
		}
		maxStep := func(x []float64) (m float64) {
			for i := 1; i < len(x); i++ {
				m = math.Max(m, math.Abs(x[i]-x[i-1]))
			}
			return m
		}
		end := len(s) - strokeFade
		fade, before := maxStep(s[end-1:]), maxStep(s[end-strokeFade-1:end])
		if fade > before {
			t.Errorf("pitch %v: largest step in the fade %v exceeds %v before it", pitch, fade, before)
		}
	}
}

func peak(x []float64) (m float64) {
	for _, v := range x {
		m = math.Max(m, math.Abs(v))
	}
	return m
}

func TestPeak(t *testing.T) {
	worst := 0.0
	for _, c := range []struct {
		prelude, minutes int
		flatLast         bool
	}{{9, 60, true}, {9, 60, false}, {3, 60, true}} {
		worst = math.Max(worst, peak(peal(c.prelude, c.minutes, c.flatLast)))
	}
	if worst > 0.9 {
		t.Errorf("69 stroke peal peaks at %.4f of full scale, above 0.9", worst)
	}
	t.Logf("69 stroke peak %.4f of full scale (unscaled %.4f); nine stroke peak %.4f, or %.4f with the last stroke flat",
		worst, worst/gain, peak(peal(9, 0, false)), peak(peal(9, 0, true)))
}

func build69() []byte {
	p, m := strokeCount(ending{code: 1}, secs(7200))
	return wav(peal(p, m, true), record(ending{code: 1}, secs(7200), p+m, plain))
}

func BenchmarkPeal69(b *testing.B) {
	for i := 0; i < b.N; i++ {
		build69()
	}
}

func TestPeal69Time(t *testing.T) {
	var d []time.Duration
	for i := 0; i < 5; i++ {
		start := time.Now()
		build69()
		d = append(d, time.Since(start))
	}
	sort.Slice(d, func(i, j int) bool { return d[i] < d[j] })
	if d[2] >= 100*time.Millisecond {
		t.Errorf("median build of the 69 stroke peal took %v, want under 100 ms", d[2])
	}
	t.Logf("69 stroke peal of a failed command, with WAV encoding: median of five %v (%v)", d[2], d)
}
