package udp

import (
	"net"
	"testing"
)

// Two copies of MSHV call themselves "MSHV". WSJT-X refuses to start a second
// instance without --rig-name, so its ids differ; MSHV has no such rule, and
// everything a decode needs — the dial frequency, the T/R period, the mode —
// used to be filed under the id alone.
//
// The consequence was reported from a real station: the second copy, on LF,
// overwrote the dial of the first, and FT8 decodes made on 14.095 came out
// labelled 2190 m — which is 136 kHz plus an audio offset, to the hertz.
func TestSameProgramIDFromTwoAddressesAreTwoInstances(t *testing.T) {
	s := &Server{}
	a := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 2237}
	b := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 2238}

	first := s.instanceLabel("MSHV", a)
	second := s.instanceLabel("MSHV", b)
	if first == second {
		t.Fatalf("two applications on different sockets share the label %q", first)
	}
	if first != "MSHV" {
		t.Fatalf("the first instance should keep the plain id, got %q", first)
	}

	// Stable: the same socket must keep its name for as long as it runs, or the
	// decodes panel would grow a new column every time a packet arrived.
	if again := s.instanceLabel("MSHV", a); again != first {
		t.Fatalf("label changed for the same address: %q then %q", first, again)
	}
	if again := s.instanceLabel("MSHV", b); again != second {
		t.Fatalf("label changed for the same address: %q then %q", second, again)
	}
}

// Distinct ids stay distinct without decoration — a station running WSJT-X and
// MSHV should not see either renamed.
func TestDifferentProgramIDsAreLeftAlone(t *testing.T) {
	s := &Server{}
	a := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 2237}
	b := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 2238}
	if got := s.instanceLabel("WSJT-X", a); got != "WSJT-X" {
		t.Fatalf("WSJT-X was renamed to %q", got)
	}
	if got := s.instanceLabel("MSHV", b); got != "MSHV" {
		t.Fatalf("MSHV was renamed to %q", got)
	}
}
