/*
 * Copyright 2021 PingCAP, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package event_bus

import (
	"testing"

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

type TestEvent struct {
}

func (te TestEvent) Name() string {
	return "TestEvent"
}

type TestErrorSubscriber struct {
}

func (ts TestErrorSubscriber) SubscribeWithError(e TestEvent) error {
	return errors.New(e.Name())
}

func TestSubscriberWithErr(t *testing.T) {
	assert := require.New(t)

	EventBus.Register(&TestErrorSubscriber{})

	err := EventBus.PostSync(TestEvent{})
	assert.True(err.Error() == "TestEvent")
}

type TestEvent1 struct {
}

func (te1 TestEvent1) Name() string {
	return "TestEvent1"
}

type TestNormal1Subscriber struct {
	testEvent int

	testEvent1 int
}

func (tn *TestNormal1Subscriber) SubscribeTestEvent(e TestEvent) {
	tn.testEvent++
}

func Int(v int) *int {
	return &v
}

func (tn *TestNormal1Subscriber) SubscribeTestEvent1(e TestEvent1) {
	tn.testEvent1++
}

type TestNormal2Subscriber struct {
	testEvent int

	testEvent1 int
}

func (tn *TestNormal2Subscriber) SubscribeTestEvent(e TestEvent) {
	tn.testEvent++
}

func (tn *TestNormal2Subscriber) SubscribeTestEvent1(e TestEvent1) {
	tn.testEvent1++
}

func TestSubscriberWithNormal(t *testing.T) {
	assert := require.New(t)

	t1 := TestNormal1Subscriber{
		testEvent:  0,
		testEvent1: 100,
	}
	EventBus.Register(&t1)

	t2 := TestNormal2Subscriber{
		testEvent:  1000,
		testEvent1: 2000,
	}
	EventBus.Register(&t2)

	err := EventBus.PostSync(TestEvent{})
	assert.Nil(err)

	assert.Equal(t1.testEvent, 1)
	assert.Equal(t2.testEvent, 1001)

	err = EventBus.PostSync(TestEvent1{})
	assert.Nil(err)
	assert.Equal(t1.testEvent, 1)
	assert.Equal(t2.testEvent, 1001)

	assert.Equal(t1.testEvent1, 101)
	assert.Equal(t2.testEvent1, 2001)
}
