package main

import (
	"bufio"
	"encoding/binary"
	"fmt"
	"io"
	"math"
)

const (
	trimSec = 0.05  // taken off both ends of every copied pause
	fadeSec = 0.010 // crossfade at each join, and fade in and out of the file
)

type span struct{ start, end int64 } // frames, end exclusive

func trimFrames(rate int) int64 { return int64(math.Round(float64(rate) * trimSec)) }
func fadeFrames(rate int) int64 { return max(1, int64(math.Round(float64(rate)*fadeSec))) }

// joinedFrames is the written length: the sum of the trimmed pauses, less
// one crossfade per join.
func joinedFrames(rate int, spans []span) int64 {
	if len(spans) == 0 {
		return 0
	}
	t, x := trimFrames(rate), fadeFrames(rate)
	var sum int64
	for _, s := range spans {
		sum += s.end - s.start - 2*t
	}
	return sum - int64(len(spans)-1)*x
}

// raisedCos rises from 0 at i = 0 towards 1 at i = n.
func raisedCos(i, n int64) float64 { return 0.5 - 0.5*math.Cos(math.Pi*float64(i)/float64(n)) }

// writeGaps streams the spans of in to out as one 16-bit file, joined with
// equal-power crossfades. Memory holds one read chunk and one crossfade tail,
// whatever the length of a pause.
func writeGaps(in *wavIn, spans []span, out io.Writer) error {
	ch := in.ch
	trim, xf := trimFrames(in.rate), fadeFrames(in.rate)
	total := joinedFrames(in.rate, spans)
	bw := bufio.NewWriterSize(out, bufSize)
	if _, err := bw.Write(wavHeader(in.rate, ch, total)); err != nil {
		return err
	}
	var pos int64
	sample := make([]byte, 2)
	emit := func(frame []float64) error {
		g := 1.0
		if pos < xf {
			g = raisedCos(pos, xf)
		}
		if r := total - 1 - pos; r < xf {
			g *= raisedCos(r, xf)
		}
		for _, v := range frame {
			s := math.Round(v * g)
			s = math.Max(-32768, math.Min(32767, s))
			binary.LittleEndian.PutUint16(sample, uint16(int16(s)))
			if _, err := bw.Write(sample); err != nil {
				return err
			}
		}
		pos++
		return nil
	}

	if err := in.rewind(); err != nil {
		return err
	}
	const chunk = 8192
	buf := make([]int16, chunk*ch)
	tail := make([]float64, xf*int64(ch))
	frame := make([]float64, ch)
	var cur int64
	last := len(spans) - 1
	for k, s := range spans {
		from, length := s.start+trim, s.end-s.start-2*trim
		if err := in.skip(from - cur); err != nil {
			return err
		}
		cur = from + length
		for j := int64(0); j < length; {
			want := min(int64(chunk), length-j)
			n, err := in.read(buf[:want*int64(ch)])
			if int64(n) < want {
				return fmt.Errorf("the recording ended early (%v)", err)
			}
			for f := 0; f < n; f++ {
				idx := j + int64(f)
				src := buf[f*ch : f*ch+ch]
				switch {
				case k > 0 && idx < xf:
					// a fades out on cos, b fades in on sin: constant power for uncorrelated noise
					t := math.Pi / 2 * float64(idx+1) / float64(xf+1)
					for c := range frame {
						frame[c] = tail[idx*int64(ch)+int64(c)]*math.Cos(t) + float64(src[c])*math.Sin(t)
					}
				case k < last && idx >= length-xf:
					for c := range src {
						tail[(idx-(length-xf))*int64(ch)+int64(c)] = float64(src[c])
					}
					continue
				default:
					for c := range frame {
						frame[c] = float64(src[c])
					}
				}
				if err := emit(frame); err != nil {
					return err
				}
			}
			j += int64(n)
		}
	}
	if pos != total {
		return fmt.Errorf("wrote %d frames, expected %d", pos, total)
	}
	return bw.Flush()
}
