package main

// The voice keyer, through an Icom's network link — the Icom face of what
// app_tci_dvk.go does for a SunSDR: selecting the radio as the "To radio"
// output hands messages to the 50003 audio session instead of a sound card.
// The same PTT before and after, the same gain, the same files.

import (
	"fmt"

	"hamlog/internal/applog"
	"hamlog/internal/audio"
	"hamlog/internal/cat"
)

// icomTXPlayer hands one message to the radio. Fetched on the CAT goroutine,
// played off it — a ten-second message must not freeze frequency, mode and
// PTT handling for ten seconds (see tciTXPlayer, which set the pattern).
func (a *App) icomTXPlayer(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
	if a.cat == nil {
		return fmt.Errorf("CAT not initialized")
	}
	type txPlayer interface {
		PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error
	}
	var player txPlayer
	err := a.cat.IcomDo(func(ic cat.IcomController) error {
		p, ok := ic.(txPlayer)
		if !ok {
			return fmt.Errorf("this radio cannot take transmit audio over its CAT link")
		}
		player = p
		return nil
	})
	if err != nil {
		return err
	}
	return player.PlayTXAudio(pcm, rate, ch, bits, stop)
}

// installIcomTXPlayer offers the network Icom as an audio output, or withdraws
// it. Withdrawing matters as much as offering — see installTCITXPlayer.
func (a *App) installIcomTXPlayer(on bool) {
	if !on {
		return // the reloadCAT preamble already cleared the network player
	}
	audio.SetNetworkPlayer(a.icomTXPlayer)
	applog.Printf("icom net: the radio is available as an audio output — the voice keyer can play to it without a cable")
}
