package rawdb

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

// Quorum

func Test_freezer_Close(t *testing.T) {
	// Close first time
	mockFreezer := newFreezerMock(t)
	err := mockFreezer.Close()
	assert.Nil(t, err)

	// Close second time should return error but do not hang sending data to freeze.quit channel
	timeout := time.After(1 * time.Second)
	errCh := make(chan error)

	go func() {
		errCh <- mockFreezer.Close()
	}()

	select {
	case <-timeout:
		t.Fatal("freezer.Close() timed out")
	case err := <-errCh:
		assert.Nil(t, err)
	}
}

// Releaser is an autogenerated mock type for the Releaser type
type releaserMock struct {
	mock.Mock
}

// Release provides a mock function with given fields:
func (_m *releaserMock) Release() error {
	ret := _m.Called()

	var r0 error
	if rf, ok := ret.Get(0).(func() error); ok {
		r0 = rf()
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

func newFreezerMock(t *testing.T) *freezer {
	mockLock := new(releaserMock)
	mockFreezer := &freezer{
		tables:       make(map[string]*freezerTable),
		instanceLock: mockLock,
		quit:         make(chan struct{}),
	}
	mockLock.On("Release").Return(nil)

	started := make(chan bool)
	go func() {
		started <- true
		<-mockFreezer.quit
	}()
	<-started

	return mockFreezer
}

// End Quorum
