package cat

import (
	"testing"

	"hamlog/internal/cat/civ"
)

// A CI-V bus can carry a second controller, and the rig answers each of them on
// the same wire. A reply addressed to somebody else must not be taken for ours —
// on an IC-7850 one arrived between a PTT command and its acknowledgement, the
// acknowledgement was never matched, and the failure was handed to JTDX as a rig
// control error.
func TestForeignCIVRepliesAreIgnored(t *testing.T) {
	const rig = 0x8E
	frames, _ := civ.Scan([]byte{
		0xFE, 0xFE, 0x01, rig, 0x1C, 0x00, 0x01, 0xFD, // to controller 01 — not ours
		0xFE, 0xFE, civ.AddrController, rig, 0xFB, 0xFD, // to us: the acknowledgement
		0xFE, 0xFE, 0x00, rig, 0x00, 0x00, 0x25, 0x09, 0x14, 0x00, 0xFD, // transceive broadcast
	})
	if len(frames) != 3 {
		t.Fatalf("scanned %d frames, want 3", len(frames))
	}
	var kept []civ.Decoded
	for _, f := range frames {
		if f.From != rig {
			continue
		}
		if f.To != civ.AddrController && f.To != 0x00 {
			continue
		}
		kept = append(kept, f)
	}
	if len(kept) != 2 {
		t.Fatalf("kept %d frames, want 2 (ours + the broadcast)", len(kept))
	}
	if kept[0].Cmd != 0xFB {
		t.Errorf("the acknowledgement was not the first kept frame: % X", kept[0].Cmd)
	}
	if kept[1].To != 0x00 {
		t.Errorf("the transceive broadcast was dropped")
	}
}
