package gff

import (
	"bytes"
	"encoding/json"
	"testing"
)

func TestRoundTripBinaryAndJSON(t *testing.T) {
	original := Document{
		FileType:    "UTC ",
		FileVersion: "V3.2",
		Root: Struct{
			Type: 0,
			Fields: []Field{
				NewField("Tag", StringValue("test_creature")),
				NewField("TemplateResRef", ResRefValue("nw_test")),
				NewField("HP", IntValue(12)),
				NewField("Position", Vector{X: 1.25, Y: 2.5, Z: 3.75}),
				NewField("Inventory", ListValue{
					{
						Type: 1,
						Fields: []Field{
							NewField("Slot", DWordValue(0)),
							NewField("ResRef", ResRefValue("itm_sword")),
						},
					},
				}),
			},
		},
	}

	var binaryBuf bytes.Buffer
	if err := Write(&binaryBuf, original); err != nil {
		t.Fatalf("write binary: %v", err)
	}

	decoded, err := Read(bytes.NewReader(binaryBuf.Bytes()))
	if err != nil {
		t.Fatalf("read binary: %v", err)
	}

	left, err := json.Marshal(original)
	if err != nil {
		t.Fatalf("marshal original json: %v", err)
	}
	right, err := json.Marshal(decoded)
	if err != nil {
		t.Fatalf("marshal decoded json: %v", err)
	}

	if string(left) != string(right) {
		t.Fatalf("roundtrip mismatch\noriginal: %s\ndecoded:  %s", left, right)
	}
}
