package main

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestScanVmixInventory(t *testing.T) {
	xml := `<vmix><version>29.0.0.48</version><inputs><input key="abc" number="12" type="GT" title="Scorebug"><text index="0" name="HomeTeam.Text">SKA</text><image index="0" name="HomeLogo.Source">c:\\logo.png</image></input></inputs></vmix>`
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/xml")
		_, _ = w.Write([]byte(xml))
	}))
	defer srv.Close()
	status, inv := scanVmix(srv.URL)
	if !status.Connected || status.Version != "29.0.0.48" {
		t.Fatalf("bad status: %+v", status)
	}
	if inv.InputCount != 1 || inv.FieldCount != 2 || len(inv.Fingerprint) != 64 {
		t.Fatalf("bad inventory: %+v", inv)
	}
	if inv.Inputs[0].Title != "Scorebug" || len(inv.Inputs[0].Fields) != 2 {
		t.Fatalf("bad input: %+v", inv.Inputs[0])
	}
}

func TestScanVmixOverlayTallyResolvesInputIdentity(t *testing.T) {
	xml := `<vmix><inputs>` +
		`<input key="geo-guid" number="16" type="GT" title="GEO">GEO</input>` +
		`<input key="score-guid" number="5" type="GT" title="SCORE">SCORE</input>` +
		`</inputs><overlays>` +
		`<overlay number="1">5</overlay>` +
		`<overlay number="2"></overlay>` +
		`<overlay number="3"></overlay>` +
		`<overlay number="4">16</overlay>` +
		`</overlays></vmix>`
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/xml")
		_, _ = w.Write([]byte(xml))
	}))
	defer srv.Close()

	overlays, connected := scanVmixOverlayTally(srv.URL)
	if !connected {
		t.Fatal("expected vMix tally connection")
	}
	if got := overlays["4"]; got.InputNumber != "16" || got.InputKey != "geo-guid" || got.InputTitle != "GEO" {
		t.Fatalf("bad overlay 4 tally: %+v", got)
	}
	if got := overlays["1"]; got.InputNumber != "5" || got.InputKey != "score-guid" {
		t.Fatalf("bad overlay 1 tally: %+v", got)
	}
	if _, ok := overlays["2"]; ok {
		t.Fatalf("empty overlay 2 must not be active: %+v", overlays["2"])
	}
}
