package antgenius

import "testing"

func TestHandleAntennaList(t *testing.T) {
	c := New("x", 9007, "")
	// Names may contain spaces — must be captured up to " tx=".
	c.handleLine("R3|0|antenna 1 name=UB VL2.3 tx=ffff rx=ffff inband=0000")
	c.handleLine("R3|0|antenna 2 name=DX Commander tx=00ff rx=00ff inband=0000")
	st := c.GetStatus()
	if len(st.Antennas) != 2 {
		t.Fatalf("got %d antennas, want 2: %+v", len(st.Antennas), st.Antennas)
	}
	if st.Antennas[0].Index != 1 || st.Antennas[0].Name != "UB VL2.3" {
		t.Errorf("antenna 1 = %+v", st.Antennas[0])
	}
	if st.Antennas[1].Name != "DX Commander" {
		t.Errorf("antenna 2 name = %q", st.Antennas[1].Name)
	}
}

func TestAntennaUnderscoreAndPlaceholder(t *testing.T) {
	c := New("x", 9007, "")
	c.handleLine("R3|0|antenna 1 name=Hex_Beam tx=ffff rx=ffff inband=0000")  // underscore → space
	c.handleLine("R3|0|antenna 4 name=Antenna_4 tx=0000 rx=0000 inband=0000") // default → filtered
	c.handleLine("R3|0|antenna 5 name=antenna 5 tx=0000 rx=0000 inband=0000") // default → filtered
	st := c.GetStatus()
	if len(st.Antennas) != 1 || st.Antennas[0].Name != "Hex Beam" {
		t.Fatalf("want only [Hex Beam], got %+v", st.Antennas)
	}
}

func TestHandlePortStatus(t *testing.T) {
	c := New("x", 9007, "")
	// Async push after "sub port all": active antenna is txant (fallback rxant).
	c.handleLine("S0|port 1 source=MANUAL band=6 rxant=2 txant=2 inband=0 inhibit=0")
	c.handleLine("S0|port 2 source=AUTO band=0 rxant=0 txant=0 inband=0 inhibit=0")
	st := c.GetStatus()
	if st.PortA != 2 {
		t.Errorf("PortA = %d, want 2", st.PortA)
	}
	if st.PortB != 0 {
		t.Errorf("PortB = %d, want 0 (none)", st.PortB)
	}
	// A "port get" reply (R-line) must parse the same way.
	c.handleLine("R15|0|port 2 source=MANUAL band=3 rxant=5 txant=5 inband=0 inhibit=0")
	if st = c.GetStatus(); st.PortB != 5 {
		t.Errorf("PortB after port get = %d, want 5", st.PortB)
	}
}

func TestPortTxFallbackToRx(t *testing.T) {
	c := New("x", 9007, "")
	c.handleLine("S0|port 1 source=MANUAL band=6 rxant=3 txant=0 inband=0 inhibit=0")
	if st := c.GetStatus(); st.PortA != 3 {
		t.Errorf("PortA = %d, want 3 (rx fallback when tx=0)", st.PortA)
	}
}

func TestKvInt(t *testing.T) {
	s := "port 1 source=MANUAL band=6 rxant=2 txant=7 inhibit=0"
	if v := kvInt(s, "txant"); v != 7 {
		t.Errorf("txant = %d, want 7", v)
	}
	if v := kvInt(s, "rxant"); v != 2 {
		t.Errorf("rxant = %d, want 2", v)
	}
	if v := kvInt(s, "missing"); v != 0 {
		t.Errorf("missing = %d, want 0", v)
	}
}
