package pubsubclient

import "sync"

type mockPubsubConn struct {
	sendMutex sync.RWMutex
	sendStub  func(typedMessage) error
	sendCalls []typedMessage

	closeMutex sync.RWMutex
	closeStub  func() error
	closeCalls int

	errch chan error
}

func newMockPubsubConn() *mockPubsubConn {
	return &mockPubsubConn{errch: make(chan error)}
}

func (c *mockPubsubConn) send(m typedMessage) error {
	c.sendMutex.Lock()
	c.sendCalls = append(c.sendCalls, m)
	c.sendMutex.Unlock()

	if c.sendStub != nil {
		return c.sendStub(m)
	}
	return nil
}

func (c *mockPubsubConn) sendCallHistory() []typedMessage {
	c.sendMutex.RLock()
	defer c.sendMutex.RUnlock()
	return c.sendCalls
}

func (c *mockPubsubConn) close() error {
	c.closeMutex.Lock()
	c.closeCalls++
	c.closeMutex.Unlock()

	if c.closeStub != nil {
		return c.closeStub()
	}
	close(c.errch)
	return nil
}

func (c *mockPubsubConn) closeCallCount() int {
	c.closeMutex.RLock()
	defer c.closeMutex.RUnlock()
	return c.closeCalls
}

func (c *mockPubsubConn) errors() chan error { return c.errch }

func (c *mockPubsubConn) forwardTo(ch chan<- *Message) {}
