package decoder

import (
	"encoding/binary"
	"math"
	"time"

	"github.com/jan/fm-rds-tx/internal/ingest"
)

const defaultSampleRateHz = 44100

func ResolveSampleRate(decodedSampleRateHz int, meta StreamMeta) int {
	if decodedSampleRateHz > 0 {
		return decodedSampleRateHz
	}
	if meta.SampleRateHz > 0 {
		return meta.SampleRateHz
	}
	return defaultSampleRateHz
}

func BuildChunk(samples []int32, channels, sampleRateHz int, seq uint64, sourceID string) ingest.PCMChunk {
	return ingest.PCMChunk{
		Samples:      samples,
		Channels:     channels,
		SampleRateHz: sampleRateHz,
		Sequence:     seq,
		Timestamp:    time.Now(),
		SourceID:     sourceID,
	}
}

func PCM16LEToPCM32(in []byte) []int32 {
	out := make([]int32, 0, len(in)/2)
	for i := 0; i+1 < len(in); i += 2 {
		v := int16(binary.LittleEndian.Uint16(in[i : i+2]))
		out = append(out, int32(v)<<16)
	}
	return out
}

func Float32ToPCM32(in []float32) []int32 {
	out := make([]int32, len(in))
	for i, sample := range in {
		if sample > 1 {
			sample = 1
		} else if sample < -1 {
			sample = -1
		}
		if sample == -1 {
			out[i] = math.MinInt32
			continue
		}
		out[i] = int32(sample * math.MaxInt32)
	}
	return out
}
