package event

import (
	"sync"
	"time"

	"github.com/mhaya/game/game_cluster/internal/mdb/eventmodels"
	mhayaLogger "github.com/mhaya/logger"
)

type EventManage struct {
	eventMap sync.Map
}

type Eventer interface {
	EventName() string
}

var (
	instance *EventManage
	once     sync.Once

	_ Eventer = &eventmodels.UserRegisterEventContent{}
	_ Eventer = &eventmodels.UserLoginEventContent{}
	_ Eventer = &eventmodels.UserUpdateInfoEventContent{}
	_ Eventer = &eventmodels.UserWithdrawEventContent{}
	_ Eventer = &eventmodels.AssetsEventContent{}
	_ Eventer = &eventmodels.InviteEventContent{}
	_ Eventer = &eventmodels.DiceEventContent{}
	_ Eventer = &eventmodels.TurntableEventContent{}
	_ Eventer = &eventmodels.JoinChannelEventContent{}
	_ Eventer = &eventmodels.FollowEventContent{}
	_ Eventer = &eventmodels.TaskFinishEventContent{}
	_ Eventer = &eventmodels.BackendOperationEventContent{}
)

func init() {
	once.Do(func() {
		instance = &EventManage{
			eventMap: sync.Map{},
		}
	})

	instance.AddEvent(new(eventmodels.UserRegisterEventContent))
	instance.AddEvent(new(eventmodels.UserLoginEventContent))
	instance.AddEvent(new(eventmodels.UserUpdateInfoEventContent))
	instance.AddEvent(new(eventmodels.UserWithdrawEventContent))
	instance.AddEvent(new(eventmodels.AssetsEventContent))
	instance.AddEvent(new(eventmodels.InviteEventContent))
	instance.AddEvent(new(eventmodels.DiceEventContent))
	instance.AddEvent(new(eventmodels.TurntableEventContent))
	instance.AddEvent(new(eventmodels.JoinChannelEventContent))
	instance.AddEvent(new(eventmodels.FollowEventContent))
	instance.AddEvent(new(eventmodels.TaskFinishEventContent))
	instance.AddEvent(new(eventmodels.BackendOperationEventContent))
}

func GetEventIdMap() *EventManage {
	return instance
}

func (em *EventManage) AddEvent(e Eventer) {
	em.eventMap.Store(e.EventName(), e)
}

func (em *EventManage) GetEvent(eventName string) Eventer {
	value, exist := em.eventMap.Load(eventName)
	if !exist {
		return nil
	}

	return value.(Eventer)
}

func (em *EventManage) PrintAllEvent() {
	// 延迟1S 以便集中输出内容
	time.Sleep(time.Second)

	mhayaLogger.Info("-------------------EventList Begin------------------------------")
	em.eventMap.Range(func(key, value any) bool {
		mhayaLogger.Infof("[event name = %s]", key)
		mhayaLogger.Infof("[event content = %#v]", value)
		return true
	})
	mhayaLogger.Info("-------------------EventList End------------------------------")
}
