package adif

import (
	"bufio"
	"strings"
	"testing"

	"hamlog/internal/qso"
)

// An exported record has to fit on its own line. ADDRESS is a multi-line field
// by the standard and callbooks fill it that way, so an OpsLog export was one
// record spread down a dozen lines with the next apparently starting in the
// middle of the page.
func TestAMultiLineValueIsWrittenOnOneLine(t *testing.T) {
	var b strings.Builder
	bw := bufio.NewWriter(&b)
	writeField(bw, "ADDRESS", "Kabul\r\n\r\n\r\n\r\nAfghanistan\r\n")
	bw.Flush()

	got := b.String()
	if strings.ContainsAny(got, "\r\n") {
		t.Fatalf("the record still breaks across lines: %q", got)
	}
	if want := "<ADDRESS:18>Kabul, Afghanistan "; got != want {
		t.Errorf("got %q, want %q", got, want)
	}
}

// And the whole record, the way an operator reads the file.
func TestARecordIsOneLine(t *testing.T) {
	hz := int64(28555000)
	rec := SingleRecordADIF(qso.QSO{
		Callsign: "T6T", Band: "10m", Mode: "SSB", FreqHz: &hz,
		Address: "Kabul\n\n\nAfghanistan", Name: "Shuravi\t(Vyacheslav)",
	})
	if n := strings.Count(strings.TrimRight(rec, "\r\n"), "\n"); n != 0 {
		t.Errorf("the record spans %d extra lines:\n%s", n, rec)
	}
	if !strings.Contains(rec, "Kabul, Afghanistan") {
		t.Errorf("the address lost its parts:\n%s", rec)
	}
	if !strings.Contains(rec, "Shuravi (Vyacheslav)") {
		t.Errorf("a tab was left in the value:\n%s", rec)
	}
}
