package data

import "testing"

type reloadableTestClient struct{ id int }

func TestReloadableReclaimsRepublishedClient(t *testing.T) {
	first := &reloadableTestClient{id: 1}
	second := &reloadableTestClient{id: 2}
	closed := map[*reloadableTestClient]int{}
	clients := newReloadable(first, func(client *reloadableTestClient) { closed[client]++ })

	clients.replace(second)
	clients.replace(first)

	if clients.retired.take(first) {
		t.Fatal("republished client remained scheduled for retirement")
	}
	clients.close()
	if closed[first] != 1 {
		t.Fatalf("active client closed %d times, want 1", closed[first])
	}
	if closed[second] != 1 {
		t.Fatalf("retired client closed %d times, want 1", closed[second])
	}
}

func TestReloadableCloseDeduplicatesHandles(t *testing.T) {
	client := &reloadableTestClient{id: 1}
	closed := 0
	clients := newReloadable(client, func(*reloadableTestClient) { closed++ })
	clients.retired.items = append(clients.retired.items, client, client)

	clients.close()
	if closed != 1 {
		t.Fatalf("client closed %d times, want 1", closed)
	}
}
