package ecs

import (
	
	
)

// observerID is the observer ID type.
type observerID uint32

// maxObserverID is used as ID for unregistered observers.
const maxObserverID = math.MaxUint32

// EventType is the type for event identifiers.
// See below for predefined event types.
//
// Use an [EventRegistry] to create custom events types.
// See [Event] and [World.Event] for using custom events.
//
// See [Observer] for details on events and observers.
type EventType uint8

// Predefined event types.
const (
	// customEvent is the highest possible EventType for custom events.
	customEvent EventType = iota + 248

	// OnCreateEntity event.
	// Emitted after an entity is created.
	OnCreateEntity

	// OnRemoveEntity event.
	// Emitted before an entity is removed.
	OnRemoveEntity

	// OnAddComponents event.
	// Emitted after components are added to an entity.
	OnAddComponents

	// OnRemoveComponents event.
	// Emitted before components are removed from an entity.
	OnRemoveComponents

	// OnSetComponents event.
	// Emitted after components are set from an entity.
	OnSetComponents

	// OnAddRelations event.
	// Emitted after relation targets are added to an entity.
	// Includes creating entities, added components as well as setting relation targets.
	OnAddRelations

	// OnRemoveRelations event.
	// Emitted before relation targets are removed from an entity.
	// Includes removing entities, removing components as well as setting relation targets.
	OnRemoveRelations
)

// EventRegistry for creating new custom event types (see [EventType]).
//
// Your application should have a single, global EventRegistry.
// Using event types from multiple registries in the same [World]
// leads to conflicts.
type EventRegistry struct {
	nextID EventType // next EventType ID
}

// NewEventType creates a new EventType for custom events.
// Custom event types should be stored in global variables.
//
// The maximum number of event types is limited to 256, with 7 predefined and 249 potential custom types.
//
// See [Event] and [World.Event] for using custom events.
func ( *EventRegistry) () EventType {
	if .nextID > customEvent {
		panic(fmt.Sprintf("reached maximum number of %d custom event types", customEvent+1))
	}
	 := .nextID
	.nextID++
	return 
}

// Event is a custom event.
//
// Create events using [World.Event].
// Create custom event types using an [EventRegistry].
type Event struct {
	world     *World    // The associated world
	eventType EventType // The event's type
	mask      bitMask   // The event's component mask
}

// For sets the event's component types. Optional.
//
// For best performance, store the event after setting component types,
// and re-use afterwards.
func ( Event) ( ...Comp) Event {
	for  := range  {
		 := TypeID(.world, [].tp)
		.mask.Set(.id)
	}
	return 
}

// Emit the event for the given entity.
func ( Event) ( Entity) {
	.world.emitEvent(&, )
}

// observerManager manages observers and distributes events.
type observerManager struct {
	observers    [][]*observerData     // Observers per event type
	hasObservers []bool                // Presence of any observers per event type
	allComps     []bitMask             // Union of all observed components per event type
	allWith      []bitMask             // Union of all "with"-components per event type
	anyNoComps   []bool                // Presence of wildcard component observers per event type
	anyNoWith    []bool                // Presence of wildcard "with" observers per event type
	pool         intPool[observerID]   // Pool for observer IDs
	indices      map[observerID]uint32 // Mapping for observer locations for fast removal
	totalCount   uint32                // Total number of observers
	maxEventType EventType             // Highest event type ID present in registered observers
}

// newObserverManager creates anew empty observerManager.
func newObserverManager() *observerManager {
	 := math.MaxUint8 + 1
	return &observerManager{
		observers:    make([][]*observerData, ),
		hasObservers: make([]bool, ),
		anyNoComps:   make([]bool, ),
		anyNoWith:    make([]bool, ),
		allComps:     make([]bitMask, ),
		allWith:      make([]bitMask, ),
		pool:         newIntPool[observerID](32),
		indices:      map[observerID]uint32{},
	}
}

// AddObserver adds an observer.
func ( *observerManager) ( *Observer,  *World) {
	if .id != maxObserverID {
		panic("observer is already registered")
	}
	if .callback == nil {
		panic("observer callback must be set via Do before registering")
	}

	.id = .pool.Get()

	.hasComps, .hasWith, .hasWithout = false, false, false

	switch .event {
	case OnAddRelations, OnRemoveRelations:
		for ,  := range .comps {
			 := TypeID(, .tp)
			if !.storage.registry.IsRelation[.id] {
				panic(fmt.Sprintf("non-relation component %d in relation observer", .id))
			}
			.compsMask.Set(.id)
			.hasComps = true
		}
	case OnCreateEntity, OnRemoveEntity:
		for ,  := range .comps {
			 := TypeID(, .tp)
			.withMask.Set(.id)
			.hasWith = true
		}
	default:
		for ,  := range .comps {
			 := TypeID(, .tp)
			.compsMask.Set(.id)
			.hasComps = true
		}
	}

	for ,  := range .with {
		 := TypeID(, .tp)
		.withMask.Set(.id)
		.hasWith = true
	}
	if .exclusive {
		.withoutMask = .withMask.Not()
		.hasWithout = true
	} else {
		for ,  := range .without {
			 := TypeID(, .tp)
			.withoutMask.Set(.id)
			.hasWithout = true
		}
	}

	.indices[.id] = uint32(len(.observers[.event]))
	.observers[.event] = append(.observers[.event], &.observerData)
	.hasObservers[.event] = true
	if .event > .maxEventType {
		.maxEventType = .event
	}
	.totalCount++

	if .hasWith {
		.allWith[.event].OrI(&.withMask)
	} else {
		.anyNoWith[.event] = true
	}

	if .event == OnCreateEntity || .event == OnRemoveEntity {
		return
	}

	if .hasComps {
		.allComps[.event].OrI(&.compsMask)
	} else {
		.anyNoComps[.event] = true
	}
}

// RemoveObserver removes an observer.
func ( *observerManager) ( *Observer) {
	if .id == maxObserverID {
		panic("observer is not registered")
	}

	,  := .indices[.id]
	if ! {
		panic("can't unregister observer, not found")
	}
	delete(.indices, .id)

	 := .observers[.event]
	[].id = maxObserverID

	 := uint32(len() - 1)
	if  !=  {
		[], [] = [], []
		.indices[[].id] = 
	}
	[] = nil
	.observers[.event] = [:]
	.hasObservers[.event] =  > 0
	.totalCount--

	var  bitMask
	.anyNoWith[.event] = false
	for ,  := range .observers[.event] {
		if !.hasWith {
			.anyNoWith[.event] = true
			break
		}
		.OrI(&.withMask)
	}
	.allWith[.event] = 

	if .event == OnCreateEntity || .event == OnRemoveEntity {
		return
	}

	var  bitMask
	.anyNoComps[.event] = false
	for ,  := range .observers[.event] {
		if !.hasComps {
			.anyNoComps[.event] = true
			break
		}
		.OrI(&.compsMask)
	}
	.allComps[.event] = 
}

// HasObservers returns whether there is any registered observer for the given event type.
func ( *observerManager) ( EventType) bool {
	return .hasObservers[]
}

func ( *observerManager) ( EventType,  *bitMask) bool {
	return .anyNoWith[] || .allWith[].ContainsAny()
}

func ( *observerManager) ( EventType, ,  *bitMask) bool {
	return (.anyNoComps[] || .allComps[].ContainsAny()) &&
		(.anyNoWith[] || .allWith[].ContainsAny())
}

func ( *observerManager) ( Entity,  *bitMask) {
	if !.hasObservers[OnCreateEntity] {
		return
	}
	.fireCreateEntity(, )
}

func ( *observerManager) ( Entity,  *bitMask) {
	if !.anyWith(OnCreateEntity, ) {
		return
	}
	 := .observers[OnCreateEntity]
	for ,  := range  {
		if .matchesWithWithout() {
			.callback()
		}
	}
}

func ( *observerManager) ( *table,  int,  *bitMask) {
	if !.anyWith(OnCreateEntity, ) {
		return
	}
	 := .observers[OnCreateEntity]
	for ,  := range  {
		if .matchesWithWithout() {
			 := .Len()
			for  := ;  < ; ++ {
				.callback(.GetEntity(uintptr()))
			}
		}
	}
}

func ( *observerManager) ( Entity,  *bitMask) {
	if !.hasObservers[OnAddRelations] {
		return
	}
	.fireCreateEntityRel(, )
}

func ( *observerManager) ( Entity,  *bitMask) {
	if !.any(OnAddRelations, , ) {
		return
	}
	 := .observers[OnAddRelations]
	for ,  := range  {
		if .matches(, ) {
			.callback()
		}
	}
}

func ( *observerManager) ( *table,  int,  *bitMask) {
	if !.any(OnAddRelations, , ) {
		return
	}
	 := .observers[OnAddRelations]
	for ,  := range  {
		if .matches(, ) {
			 := .Len()
			for  := ;  < ; ++ {
				.callback(.GetEntity(uintptr()))
			}
		}
	}
}

func ( *observerManager) ( Entity,  *bitMask) {
	if !.anyWith(OnRemoveEntity, ) {
		return
	}
	 := .observers[OnRemoveEntity]
	for ,  := range  {
		if .matchesWithWithout() {
			.callback()
		}
	}
}

func ( *observerManager) ( *table,  *bitMask) {
	if !.anyWith(OnRemoveEntity, ) {
		return
	}
	 := .observers[OnRemoveEntity]
	for ,  := range  {
		if .matchesWithWithout() {
			 := .Len()
			for  := range  {
				.callback(.GetEntity(uintptr()))
			}
		}
	}
}

func ( *observerManager) ( Entity,  *bitMask) {
	if !.any(OnRemoveRelations, , ) {
		return
	}
	 := .observers[OnRemoveRelations]
	for ,  := range  {
		if .matches(, ) {
			.callback()
		}
	}
}

func ( *observerManager) ( *table,  *bitMask) {
	if !.any(OnRemoveRelations, , ) {
		return
	}
	 := .observers[OnRemoveRelations]
	for ,  := range  {
		if .matches(, ) {
			 := .Len()
			for  := range  {
				.callback(.GetEntity(uintptr()))
			}
		}
	}
}

func ( *observerManager) ( EventType,  Entity,  *bitMask,  *bitMask) {
	if !.hasObservers[] {
		return
	}
	.fireAdd(, , , )
}

func ( *observerManager) ( EventType,  Entity,  *bitMask,  *bitMask) {
	if !.anyNoComps[] &&
		(!.allComps[].ContainsAny() || .Contains(&.allComps[])) {
		return
	}
	if !.anyWith(, ) {
		return
	}
	 := .observers[]
	for ,  := range  {
		if .hasComps && (!.Contains(&.compsMask) || .ContainsAny(&.compsMask)) {
			continue
		}
		if .matchesWithWithout() {
			.callback()
		}
	}
}

func ( *observerManager) ( EventType,  *table, ,  uint32,  *bitMask,  *bitMask) {
	if !.anyNoComps[] &&
		(!.allComps[].ContainsAny() || .Contains(&.allComps[])) {
		return
	}
	if !.anyWith(, ) {
		return
	}
	 := .observers[]
	for ,  := range  {
		if .hasComps && (!.Contains(&.compsMask) || .ContainsAny(&.compsMask)) {
			continue
		}
		if .matchesWithWithout() {
			for  := ;  < ; ++ {
				.callback(.GetEntity(uintptr()))
			}
		}
	}
}

func ( *observerManager) ( EventType,  Entity,  *bitMask,  *bitMask) {
	if !.anyNoComps[] &&
		(!.allComps[].ContainsAny() || .Contains(&.allComps[])) {
		return
	}
	if !.anyWith(, ) {
		return
	}
	 := .observers[]
	for ,  := range  {
		if .hasComps && (.Contains(&.compsMask) || !.ContainsAny(&.compsMask)) {
			continue
		}
		if .matchesWithWithout() {
			.callback()
		}
	}
}

func ( *observerManager) ( EventType,  *table,  int,  *bitMask,  *bitMask) {
	if !.anyNoComps[] &&
		(!.allComps[].ContainsAny() || .Contains(&.allComps[])) {
		return
	}
	if !.anyWith(, ) {
		return
	}
	 := .observers[]
	for ,  := range  {
		if .hasComps && (.Contains(&.compsMask) || !.ContainsAny(&.compsMask)) {
			continue
		}
		if .matchesWithWithout() {
			for  := range  {
				.callback(.GetEntity(uintptr()))
			}
		}
	}
}

func ( *observerManager) ( Entity,  *bitMask,  *bitMask) {
	if !.any(OnSetComponents, , ) {
		return
	}
	 := .observers[OnSetComponents]
	for ,  := range  {
		if .matches(, ) {
			.callback()
		}
	}
}

func ( *observerManager) ( EventType,  Entity,  *bitMask,  *bitMask) {
	if !.any(, , ) {
		return
	}
	 := .observers[]
	for ,  := range  {
		if .matches(, ) {
			.callback()
		}
	}
}

func ( *observerManager) ( EventType,  *table, ,  int,  *bitMask,  *bitMask) {
	if !.any(, , ) {
		return
	}
	 := .observers[]
	for ,  := range  {
		if .matches(, ) {
			for  := ;  < ; ++ {
				.callback(.GetEntity(uintptr()))
			}
		}
	}
}

func ( *observerManager) ( EventType,  Entity, ,  *bitMask) {
	if !.any(, , ) {
		return
	}
	 := .observers[]
	for ,  := range  {
		if .matches(, ) {
			.callback()
		}
	}
}

// Reset the observer manager.
func ( *observerManager) () {
	if len(.indices) == 0 {
		.maxEventType = 0
		return
	}

	for  := range .maxEventType + 1 {
		if !.hasObservers[] {
			continue
		}
		 := .observers[]
		for ,  := range  {
			delete(.indices, .id)
			.id = maxObserverID
		}
		.observers[] = .observers[][:0]
		.hasObservers[] = false
		.allComps[].Reset()
		.allWith[].Reset()
		.anyNoComps[] = false
		.anyNoWith[] = false
	}

	.pool.Reset()
	.totalCount = 0
	.maxEventType = 0
}