package main

import "testing"

// The whole point of the signature is that pressing Save in Preferences must
// not drop the rig — and with it every WSJT-X/JTDX client of the shared CAT
// server, mid-QSO, with an error box. Only a change to the LINK may reconnect.
func TestCatLinkSigIgnoresNonLinkSettings(t *testing.T) {
	base := CATSettings{
		Enabled: true, Backend: "flex", FlexHost: "192.168.1.20", FlexPort: 4992,
		PollMs: 250, DigitalDefault: "FT8",
	}
	same := base
	// Everything here is applied to the RUNNING manager; none of it justifies a
	// reconnection, and a spot option in particular must not wipe the panadapter
	// (a Flex reconnect clears every spot on it).
	same.PollMs = 500
	same.DelayMs = 20
	same.OffsetOn = true
	same.OffsetHz = 116_000_000
	same.FlexDecodeSpots = !base.FlexDecodeSpots
	same.FlexDecodeSecs = 300
	same.FlexDVKDax = !base.FlexDVKDax
	same.PTTHotkeyEnabled = true
	same.PTTHotkey = "Pause"
	if catLinkSig(base) != catLinkSig(same) {
		t.Errorf("non-link settings changed the signature:\n%s\n%s", catLinkSig(base), catLinkSig(same))
	}

	// And the ones that DO describe the connection must still force a restart.
	for name, mutate := range map[string]func(*CATSettings){
		"backend":     func(c *CATSettings) { c.Backend = "kenwood" },
		"flex host":   func(c *CATSettings) { c.FlexHost = "192.168.1.21" },
		"flex port":   func(c *CATSettings) { c.FlexPort = 4993 },
		"serial port": func(c *CATSettings) { c.Backend = "yaesu"; c.YaesuPort = "COM7" },
		"baud":        func(c *CATSettings) { c.Backend = "yaesu"; c.YaesuBaud = 19200 },
		"civ address": func(c *CATSettings) { c.Backend = "icom"; c.IcomAddr = 152 },
		"disabled":    func(c *CATSettings) { c.Enabled = false },
	} {
		c := base
		mutate(&c)
		if catLinkSig(c) == catLinkSig(base) {
			t.Errorf("%s did not change the signature — the rig would never reconnect", name)
		}
	}
}

// The share server is the thing WSJT-X actually holds a socket to: restarting
// it is what produced the error box, so it has a signature of its own.
func TestCatShareSig(t *testing.T) {
	base := CATSettings{Enabled: true, ShareEnabled: true, ShareProto: "rigctl", SharePort: 4532}
	other := base
	other.FlexHost = "10.0.0.5" // a rig-link change must not restart the server
	if catShareSig(base) != catShareSig(other) {
		t.Errorf("a rig-link change restarted the share server")
	}
	moved := base
	moved.SharePort = 4533
	if catShareSig(base) == catShareSig(moved) {
		t.Errorf("a new port must restart the server")
	}
	off := base
	off.ShareEnabled = false
	if catShareSig(off) != "off" || catShareSig(off) == catShareSig(base) {
		t.Errorf("switching sharing off must be a change")
	}
	// CAT off means the server has nothing to serve, whatever the share fields say.
	catOff := base
	catOff.Enabled = false
	if catShareSig(catOff) != "off" {
		t.Errorf("share signature with CAT off = %q, want \"off\"", catShareSig(catOff))
	}
}
