package protocol

import "bytes"
import "testing"

func TestMessageGeminiBodyEnd (test *testing.T) {
	conduit := new(bytes.Buffer)
	message := MessageGeminiBodyEnd {
		ID: 493234,
	}
	message.Send(conduit)

	ty, err := ReadType(conduit)
	if err != nil               { test.Fatal("when reading type code:", err) }
	if ty  != TypeGeminiBodyEnd { test.Fatal("expected", TypeGeminiBodyEnd, "got", ty) }

	got, err := ReadMessageGeminiBodyEnd(conduit)
	if err != nil { test.Fatal("when reading message:", err) }

	equal := message.ID == got.ID
	
	if !equal { test.Fatal("structures not equal") }

	if conduit.Len() != 0 {
		test.Fatal("buffer len", conduit.Len(), "instead of 0")
	}
}

func TestMessageGeminiBodySegment (test *testing.T) {
	conduit := new(bytes.Buffer)
	message := MessageGeminiBodySegment {
		ID:   22441,
		Data: makeTestBuffer(10301),
	}
	message.Send(conduit)

	ty, err := ReadType(conduit)
	if err != nil                   { test.Fatal("when reading type code:", err) }
	if ty  != TypeGeminiBodySegment { test.Fatal("expected", TypeGeminiBodySegment, "got", ty) }

	got, err := ReadMessageGeminiBodySegment(conduit)
	if err != nil { test.Fatal("when reading message:", err) }

	equal :=
		message.ID == got.ID &&
		sliceEqual(message.Data, got.Data)
	
	if !equal { test.Fatal("structures not equal") }

	if conduit.Len() != 0 {
		test.Fatal("buffer len", conduit.Len(), "instead of 0")
	}
}

func TestMessageGeminiRequest (test *testing.T) {
	conduit := new(bytes.Buffer)
	message := MessageGeminiRequest {
		ID:      9994562,
		Address: "some.thing",
		URL:     "gemini://example.com/hahaha",
	}
	message.Send(conduit)

	ty, err := ReadType(conduit)
	if err != nil               { test.Fatal("when reading type code:", err) }
	if ty  != TypeGeminiRequest { test.Fatal("expected", TypeGeminiRequest, "got", ty) }

	got, err := ReadMessageGeminiRequest(conduit)
	if err != nil { test.Fatal("when reading message:", err) }

	equal :=
		message.ID      == got.ID      &&
		message.Address == got.Address &&
		message.URL     == got.URL
	
	if !equal { test.Fatal("structures not equal") }

	if conduit.Len() != 0 {
		test.Fatal("buffer len", conduit.Len(), "instead of 0")
	}
}

func TestMessageGeminiResponse (test *testing.T) {
	conduit := new(bytes.Buffer)
	message := MessageGeminiResponse {
		ID:     77777,
		Status: 20,
		Meta:   "text/gemini",
	}
	message.Send(conduit)

	ty, err := ReadType(conduit)
	if err != nil                { test.Fatal("when reading type code:", err) }
	if ty  != TypeGeminiResponse { test.Fatal("expected", TypeGeminiResponse, "got", ty) }

	got, err := ReadMessageGeminiResponse(conduit)
	if err != nil { test.Fatal("when reading message:", err) }

	equal :=
		message.ID     == got.ID     &&
		message.Status == got.Status &&
		message.Meta   == got.Meta
	
	if !equal { test.Fatal("structures not equal") }

	if conduit.Len() != 0 {
		test.Fatal("buffer len", conduit.Len(), "instead of 0")
	}
}