package udp

import (
	"bytes"
	"testing"
)

// The wire format, byte for byte. A malformed Free Text is discarded in silence
// by the far end, exactly like a malformed Reply — so a wrong byte here shows up
// as a button that does nothing.
func TestEncodeFreeText(t *testing.T) {
	got := EncodeFreeText("JTDX", "73 GL", true)
	want := []byte{
		0xad, 0xbc, 0xcb, 0xda, // magic
		0x00, 0x00, 0x00, 0x02, // schema 2
		0x00, 0x00, 0x00, 0x09, // type 9 — Free Text
		0x00, 0x00, 0x00, 0x04, 'J', 'T', 'D', 'X',
		0x00, 0x00, 0x00, 0x05, '7', '3', ' ', 'G', 'L',
		0x01, // send now
	}
	if !bytes.Equal(got, want) {
		t.Errorf("EncodeFreeText\n got %#v\nwant %#v", got, want)
	}
}

// send=false fills the box without keying — the difference is one byte, and
// getting it backwards would transmit when the operator only meant to prepare.
func TestEncodeFreeTextWithoutSending(t *testing.T) {
	got := EncodeFreeText("MSHV", "", false)
	if got[len(got)-1] != 0x00 {
		t.Errorf("send flag = %#x, want 0 — this would transmit unasked", got[len(got)-1])
	}
	// An empty text is a zero-length QString, never the -1 that means null:
	// WSJT-X drops a packet with a null where it expects text.
	if !bytes.Equal(got[len(got)-5:len(got)-1], []byte{0, 0, 0, 0}) {
		t.Errorf("empty text was not encoded as a zero-length string: % X", got)
	}
}

func TestSendFreeTextRejectsEmptyID(t *testing.T) {
	m := &Manager{}
	if err := m.SendFreeText("  ", "73", true); err == nil {
		t.Fatal("expected an error for a blank program id")
	}
}
