package main

import (
	"fmt"
	"math"
	"strconv"
	"strings"
)

const (
	width    = 64
	labelLen = 11
	nameMax  = 30
	rule     = "================================================================"
	legend   = "A silent recording means the files are the same."
	imprint  = "normal is dead"
)

// form is what the sheet needs besides the result.
type form struct {
	date         string // YYYY-MM-DD
	nameA, nameB string // paths as given
	a, b         file
	single       bool
	wavPath      string // "" when no WAV was written
}

func sheet(f form, res result) string {
	v := res.v
	var lines []string
	add := func(label, value string) { lines = append(lines, row(label, value)) }

	lines = append(lines, "NULL TEST"+strings.Repeat(" ", 18)+f.date+strings.Repeat(" ", 18)+"Form NT-1", rule)
	lines = append(lines, right(row("A", shorten(f.nameA)), bytesText(len(f.a.b))))
	if f.single {
		add("B", "(none)")
		add("Method", "A through the string, alone")
	} else {
		lines = append(lines, right(row("B", shorten(f.nameB)), bytesText(len(f.b.b))))
		add("Method", "A and B each through the string, then B taken from A")
	}
	add("Rate", "1 byte = 1 sample, 44,100 a second, 16-bit mono")
	lines = append(lines, "")

	switch {
	case f.single:
		add("Result", "RENDERED")
		for _, l := range []string{"First", "Last", "Differing", "Length"} {
			add(l, "n/a")
		}
	case v.identical():
		add("Result", "IDENTICAL")
		for _, l := range []string{"First", "Last", "Differing"} {
			add(l, "none")
		}
		add("Length", "same")
	default:
		add("Result", "DIFFERENT")
		add("First", where(f, v.first))
		add("Last", where(f, v.last))
		add("Differing", plural(v.count, "position")+" in "+plural(v.runs, "run"))
		add("Length", lengthText(len(f.a.b), len(f.b.b)))
	}

	if res.rings == 0 {
		add("Rings", "none")
	} else {
		add("Rings", fmt.Sprintf("%d, longest %.1f s", res.rings, res.longest))
	}
	if v.identical() {
		add("Recording", mmss(res.w)+" to "+mmss(res.e)+" of the file, no ring-out")
		add("Level", "none, exactly zero")
	} else {
		add("Recording", mmss(res.w)+" to "+mmss(res.e)+" of the file, then 4.0 s ring-out")
		peak := 20 * math.Log10(res.peak)
		add("Level", fmt.Sprintf("peak %+.1f dBFS before make-up, %+.1f dB applied", peak, headroom-peak))
	}
	if f.wavPath == "" {
		add("File", "not written")
	} else {
		add("File", shorten(f.wavPath)+", "+mmss(res.t))
	}
	lines = append(lines, rule)

	hz, cents := tuning()
	add("Tuning", fmt.Sprintf("String A2, nominal 110.00 Hz, as found %.2f Hz.", hz))
	add("", fmt.Sprintf("Out by %+.1f cents. Not adjusted.", cents))
	lines = append(lines, right(legend, imprint))
	return strings.Join(lines, "\n") + "\n"
}

func row(label, value string) string { return fmt.Sprintf("%-*s%s", labelLen, label, value) }

// right sets text so that it ends at column 64.
func right(left, text string) string {
	return left + strings.Repeat(" ", max(1, width-len(left)-len(text))) + text
}

// shorten keeps the sheet ASCII and in its columns: any other character
// shows as ?, and a long path keeps only its last 27 characters.
func shorten(path string) string {
	var sb strings.Builder
	for _, c := range path {
		if c < ' ' || c > '~' {
			c = '?'
		}
		sb.WriteRune(c)
	}
	s := sb.String()
	if len(s) > nameMax {
		return "..." + s[len(s)-(nameMax-3):]
	}
	return s
}

// where names a differing position the way cmp counts bytes, or as the end
// of the file whose end mark sits there.
func where(f form, p int) string {
	t := mmss(p)
	la, lb := len(f.a.b), len(f.b.b)
	if la != lb {
		short, long, ls, ll := "A", "B", la, lb
		if lb < la {
			short, long, ls, ll = "B", "A", lb, la
		}
		if p == ls {
			return "end of " + short + ", after byte " + commas(ls) + ", file time " + t
		}
		if p == ll {
			return "end of " + long + ", after byte " + commas(ll) + ", file time " + t
		}
	}
	return "byte " + commas(p+1) + ", file time " + t
}

func lengthText(la, lb int) string {
	switch {
	case lb > la:
		return "B is " + plural(lb-la, "byte") + " longer"
	case lb < la:
		return "B is " + plural(la-lb, "byte") + " shorter"
	}
	return "same"
}

func bytesText(n int) string { return plural(n, "byte") }

func plural(n int, word string) string {
	if n == 1 {
		return "1 " + word
	}
	return commas(n) + " " + word + "s"
}

func commas(n int) string {
	s := strconv.Itoa(n)
	for i := len(s) - 3; i > 0; i -= 3 {
		s = s[:i] + "," + s[i:]
	}
	return s
}

// mmss is p samples as m:ss.t, the tenth truncated.
func mmss(p int) string {
	tenths := p * 10 / FS
	return fmt.Sprintf("%d:%02d.%d", tenths/600, (tenths/10)%60, tenths%10)
}
