package main

import (
	"fmt"
	"io"
	"math"
	"strings"
	"text/tabwriter"
)

const lineMax = 64

// doc is everything the minutes print.
type doc struct {
	name, dated, out string
	rate, ch         int
	frames           int64
	minSec, above    float64
	res              result
	gapsFrames       int64 // 0 when nothing was written
}

type row struct{ label, text string }

// block aligns labels in one column and wraps the text to the 64 column grid.
func block(w io.Writer, indent string, pad int, rows []row, wrapText bool) {
	width := 0
	for _, r := range rows {
		width = max(width, len(r.label))
	}
	budget := lineMax - len(indent) - width - pad
	tw := tabwriter.NewWriter(w, 0, 0, pad, ' ', 0)
	for _, r := range rows {
		lines := []string{r.text}
		if wrapText {
			lines = wrap(r.text, budget)
		}
		for i, l := range lines {
			label := ""
			if i == 0 {
				label = r.label
			}
			fmt.Fprintf(tw, "%s%s\t%s\n", indent, label, l)
		}
	}
	tw.Flush()
}

// wrap fills lines up to width. The last two words travel together, so a
// count is never parted from its noun ("621 pauses.", "the file.").
func wrap(s string, width int) []string {
	words := strings.Fields(s)
	if n := len(words); n >= 2 && len(words[n-2])+1+len(words[n-1]) <= width {
		words = append(words[:n-2], words[n-2]+" "+words[n-1])
	}
	var lines []string
	cur := ""
	for _, word := range words {
		if cur != "" && len(cur)+1+len(word) > width {
			lines = append(lines, cur)
			cur = word
		} else if cur == "" {
			cur = word
		} else {
			cur += " " + word
		}
	}
	return append(lines, cur)
}

func secs(frames int64, rate int) float64 { return float64(frames) / float64(rate) }

// clock is HH:MM:SS.t with the tenths truncated, so a start is never late.
func clock(frames int64, rate int) string {
	t := frames * 10 / int64(rate)
	return fmt.Sprintf("%02d:%02d:%02d.%d", t/36000, t/600%60, t/10%60, t%10)
}

func length(frames int64, rate int) string { return fmt.Sprintf("%.1f s", secs(frames, rate)) }

// dur is a total: 18.2 s, 41 min 07 s, 2 h 03 min 41 s.
func dur(s float64) string {
	if math.Round(s*10)/10 < 60 {
		return fmt.Sprintf("%.1f s", s)
	}
	n := int64(math.Round(s))
	if n < 3600 {
		return fmt.Sprintf("%d min %02d s", n/60, n%60)
	}
	return fmt.Sprintf("%d h %02d min %02d s", n/3600, n/60%60, n%60)
}

func plural(n int) string {
	if n == 1 {
		return "pause"
	}
	return "pauses"
}

func level(db float64) string {
	if math.IsInf(db, -1) {
		return "-inf"
	}
	return fmt.Sprintf("%.1f dB", db)
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func writeDoc(w io.Writer, d doc) {
	total := secs(d.frames, d.rate)
	channels := "1 channel"
	if d.ch > 1 {
		channels = fmt.Sprintf("%d channels", d.ch)
	}
	fmt.Fprint(w, "Minutes\n\n")
	block(w, "", 2, []row{
		{"Meeting:", d.name},
		{"Dated:", d.dated},
		{"Length:", fmt.Sprintf("%s (%d Hz, %s, 16-bit)", dur(total), d.rate, channels)},
		{"Present:", "(none recorded)"},
	}, false)

	quiet := fmt.Sprintf("no more than %.1f dB over the floor (%.1f dBFS).", d.above, d.res.quietDB)
	if d.res.digitalOnly {
		quiet = fmt.Sprintf("digital zero only: the floor is above %.0f dBFS.", floorCeilingDBFS)
	}
	fmt.Fprint(w, "\nRule\n")
	block(w, "  ", 3, []row{
		{"Floor", fmt.Sprintf("%.1f dBFS: the quietest tenth of the 20 ms windows that are not digital zero.", d.res.floorDB)},
		{"Quiet", quiet},
		{"Pause", fmt.Sprintf("quiet for at least %.1f s.", d.minSec)},
		{"Copied", fmt.Sprintf("to %s when room tone fills 90%% or more of the pause, less %.2f s trimmed from each end.", d.out, trimSec)},
	}, true)

	ps := d.res.pauses
	fmt.Fprint(w, "\nItems\n")
	if len(ps) == 0 {
		fmt.Fprintf(w, "  No pause of %.1f s or longer was found at these settings.\n", d.minSec)
	} else {
		tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
		fmt.Fprint(tw, "  Item\tStart\tLength\tLevel\tTone\tCopied\n")
		for i, p := range ps {
			fmt.Fprintf(tw, "  %d.\t%s\t%s\t%s\t%d%%\t%s\n", i+1, clock(p.startFrame, d.rate),
				length(p.frames, d.rate), level(p.level), p.tone, yesNo(p.copied))
		}
		tw.Flush()
	}

	var dead, lost int64
	longest, nLost, nCopied := 0, 0, 0
	for i, p := range ps {
		dead += p.frames
		if p.frames > ps[longest].frames {
			longest = i
		}
		if p.copied {
			nCopied++
		} else {
			nLost++
			lost += p.frames
		}
	}
	totals := []row{{"Dead air", fmt.Sprintf("%s of %s (%.1f%%) in %d %s.",
		dur(secs(dead, d.rate)), dur(total), 100*float64(dead)/float64(d.frames), len(ps), plural(len(ps)))}}
	if len(ps) > 0 {
		p := ps[longest]
		totals = append(totals, row{"Longest", fmt.Sprintf("%s, item %d, at %s.",
			length(p.frames, d.rate), longest+1, clock(p.startFrame, d.rate))})
	}
	if nLost > 0 {
		totals = append(totals, row{"No room tone", fmt.Sprintf("%d %s, %s: digital zero in the file.",
			nLost, plural(nLost), dur(secs(lost, d.rate)))}, row{"", "Not copied."})
	}
	if d.gapsFrames > 0 {
		totals = append(totals, row{"Room tone", fmt.Sprintf("%s, %s, %d %s.",
			d.out, dur(secs(d.gapsFrames, d.rate)), nCopied, plural(nCopied))})
	}
	fmt.Fprint(w, "\nTotals\n")
	block(w, "  ", 3, totals, true)
	fmt.Fprint(w, "\nnormal is dead\n")
}
