package desync

import (
	"context"
	"io"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestProtocolServer(t *testing.T) {
	r1, w1 := io.Pipe()
	r2, w2 := io.Pipe()

	server := NewProtocol(r1, w2)

	// Test data
	uncompressed := []byte{4, 3, 2, 1}
	chunkIn := NewChunk(uncompressed)
	id := chunkIn.ID()
	store := &TestStore{}
	store.StoreChunk(chunkIn)

	ps := NewProtocolServer(r2, w1, store)

	go ps.Serve(context.Background())

	// Client
	flags, err := server.Initialize(CaProtocolPullChunks)
	require.NoError(t, err)
	require.NotZero(t, flags&CaProtocolReadableStore, "server not offering chunks")

	// Should find this chunk
	chunk, err := server.RequestChunk(id)
	require.NoError(t, err)
	b, _ := chunk.Data()
	require.Equal(t, uncompressed, b)

	// This one's missing
	_, err = server.RequestChunk(ChunkID{0})
	require.IsType(t, ChunkMissing{}, err)
}
