package ecs

import (
	
	

	
)

// World is the central type holding entity and component data, as well as resources.
type World struct {
	stats     *stats.World // World statistics, for re-use
	resources Resources    // Registered resources
	storage   storage      // The world's storage
}

// NewWorld creates a new [World].
//
// Accepts zero, one or two arguments.
// The first argument is the initial capacity of the world, and of normal archetypes.
// The second argument is the initial capacity of relation archetypes.
// If only one argument is provided, it is used for both capacities.
// If no arguments are provided, the defaults are 1024 and 128, respectively.
func ( ...int) *World {
	return &World{
		storage:   newStorage(16, ...),
		resources: newResources(),
		stats:     &stats.World{},
	}
}

// NewEntity creates a new [Entity] without any components.
func ( *World) () Entity {
	.checkLocked()

	,  := .storage.createEntity(0)
	.storage.observers.FireCreateEntityIfHas(, &.storage.archetypes[0].mask)
	return 
}

// NewEntities creates a batch of new entities without any components, running the given callback function on each.
// The callback function can be nil.
func ( *World) ( int,  func( Entity)) {
	.checkLocked()
	, ,  := .newEntities(, nil, nil, 0)

	 := .storage.observers.HasObservers(OnCreateEntity)
	 :=  ||  != nil
	var  uint8
	if  {
		 = .lock()
	}

	if  != nil {
		 := &.storage.tables[]
		for  := range  {
			 := uintptr( + )
			(
				.GetEntity(),
			)
		}
	}

	if  {
		 := &.storage.tables[]
		 := &.storage.archetypes[.archetype].mask
		.storage.observers.FireCreateEntityBatch(, , )
	}
	if  {
		.unlock()
	}
}

// CopyEntity copies an entity with all its components.
//
// Creates a new entity and copies the memory of all components.
// Note that pointer-like fields in components (incl. slices and maps)
// are copied shallow. I.e. they will point to the same address as the original.
func ( *World) ( Entity) Entity {
	.checkLocked()

	 := &.storage
	 := .entityPool.Get()

	 := .entities[.id]
	 := &.tables[.table]

	 := .Add()
	if int(.id) == len(.entities) {
		.entities = append(.entities, entityIndex{table: .table, row: })
		.isTarget = append(.isTarget, false)
	} else {
		.entities[.id] = entityIndex{table: .table, row: }
	}

	 := &.archetypes[.archetype]

	.CopyAll(, , .row)

	.storage.observers.FireCreateEntityIfHas(, &.mask)
	if .HasRelations() {
		.storage.observers.FireCreateEntityRelIfHas(, &.mask)
	}
	return 
}

// Alive return whether the given entity is alive.
//
// In Ark, entities are returned to a pool when they are removed from the world.
// These entities can be recycled, with the same ID ([Entity.ID]), but an incremented generation ([Entity.Gen]).
// This allows to determine whether an entity held by the user is still alive, despite it was potentially recycled.
func ( *World) ( Entity) bool {
	return .storage.entityPool.Alive()
}

// RemoveEntity removes the given entity from the world.
func ( *World) ( Entity) {
	.checkLocked()
	.storage.RemoveEntity()
}

// RemoveEntities removes all entities matching the given batch filter,
// running the given function on each. The function can be nil.
func ( *World) ( Batch,  func( Entity)) {
	.checkLocked()

	 := .storage.observers.HasObservers(OnRemoveEntity)
	 := .storage.observers.HasObservers(OnRemoveRelations)
	 :=  ||  ||  != nil
	var  uint8
	if  {
		 = .lock()
	}

	 := .storage.getBatchTables(&)

	if  != nil {
		for ,  := range  {
			 := &.storage.tables[]
			 := uintptr(.Len())
			var  uintptr
			for  = range  {
				(.GetEntity())
			}
		}
	}

	if  ||  {
		if  {
			for ,  := range  {
				 := &.storage.tables[]
				 := &.storage.archetypes[.archetype].mask
				.storage.observers.FireRemoveEntityBatch(, )
			}
		}
		if  {
			for ,  := range  {
				 := &.storage.tables[]
				if !.HasRelations() {
					continue
				}
				 := &.storage.archetypes[.archetype].mask
				.storage.observers.FireRemoveEntityRelBatch(, )
			}
		}
	}

	 := .storage.slices.entitiesCleanup
	for ,  := range  {
		 := &.storage.tables[]
		 := uintptr(.Len())
		var  uintptr
		for  = range  {
			 := .GetEntity()
			if .storage.isTarget[.id] {
				 = append(, )
			}
			.storage.entities[.id].table = maxTableID
			.storage.entityPool.Recycle()
		}
		.Reset()
	}

	.storage.slices.tables = [:0]

	for ,  := range  {
		.storage.cleanupArchetypes()
		.storage.isTarget[.id] = false
	}
	.storage.slices.entitiesCleanup = [:0]

	if  {
		.unlock()
	}
}

// IsLocked returns whether the world is locked by any queries.
func ( *World) () bool {
	return .storage.locks.IsLocked()
}

// Resources of the world.
// Resources are component-like data that is not associated to an entity, but unique to the world.
//
// This is only required for unsafe/id-based usage of resources.
// For the safe API, see [Resource], [AddResource] and [GetResource].
func ( *World) () *Resources {
	return &.resources
}

// Unsafe provides access to Ark's unsafe, ID-based API.
// For details, see [Unsafe].
func ( *World) () Unsafe {
	return Unsafe{
		world: ,
	}
}

// Event creates a new event of the given type.
//
// The event can be further configured using [Event.For].
// It must be emitted using [Event.Emit] to have an effect.
//
// See [Event] and [Observer] for details.
func ( *World) ( EventType) Event {
	if  > customEvent {
		panic("only custom events can be emitted manually")
	}
	return Event{
		world:     ,
		eventType: ,
	}
}

// Reset removes all entities and resources from the world,
// and un-registers all cached filters and observers.
//
// Does NOT free reserved memory, remove archetypes, or clear the registry.
// However, it removes archetypes with a relation component.
//
// Can be used to run systematic simulations without the need to re-allocate memory for each run.
// Accelerates re-populating the world by a factor of 2-3.
func ( *World) () {
	.checkLocked()

	.storage.Reset()
	.resources.reset()
}

// Stats reports statistics for inspecting the World.
//
// The underlying [stats.World] object is re-used and updated between calls.
// The returned pointer should thus not be stored for later analysis.
// Rather, the required data should be extracted immediately.
func ( *World) () *stats.World {
	.stats.Entities = stats.Entities{
		Used:     .storage.entityPool.Len(),
		Total:    .storage.entityPool.Cap(),
		Recycled: .storage.entityPool.Available(),
		Capacity: .storage.entityPool.TotalCap(),
	}
	 := len(.stats.ComponentTypes)
	 := len(.storage.registry.Components)
	if  !=  {
		 := append([]reflect.Type{}, .storage.registry.Types[:]...)
		 := make([]string, len())
		for ,  := range  {
			[] = .Name()
		}
		.stats.ComponentTypes = 
		.stats.ComponentTypeNames = 
	}

	 := cap(.storage.entities)*int(entityIndexSize) + .storage.entityPool.TotalCap()*int(entitySize)
	 := .storage.entityPool.Len() * int(entityIndexSize+entitySize)

	 := int32(len(.stats.Archetypes))
	 := int32(len(.storage.archetypes))
	var  int32
	for  = range  {
		 := &.storage.archetypes[]
		 := &.stats.Archetypes[]
		.UpdateStats(, &.storage)
		 += .Memory
		 += .MemoryUsed
	}
	for  = ;  < ; ++ {
		 := &.storage.archetypes[]
		.stats.Archetypes = append(.stats.Archetypes, .Stats(&.storage))
		 := &.stats.Archetypes[]
		 += .Memory
		 += .MemoryUsed
	}

	.stats.Locked = .IsLocked()
	.stats.Memory = 
	.stats.MemoryUsed = 
	.stats.CachedFilters = len(.storage.cache.filters)
	.stats.Observers = int(.storage.observers.totalCount)

	return .stats
}

// Shrink reduces memory usage by shrinking the capacity of archetype tables.
// Capacity is reduced to the next power-of-2 of what is occupied,
// but never below the initial capacities specified during world initialization.
// Further, it frees empty tables of archetypes with relations.
//
// The optional stopAfter argument sets a time limit for the shrink operation.
// This allows the method to terminate early if the time budget is exceeded,
// which is especially useful in real-time environments (e.g., games or simulations)
// where maintaining frame rate is critical.
//
// If the time limit is reached before all shrink operations are completed,
// the method returns true to indicate that further shrink work remains.
// This enables incremental cleanup across multiple frames or update cycles.
//
// Note that timer resolution is limited, particularly on Windows.
// On Windows, the shortest effective time limit should be around 0.5ms,
// while it is in the range of microseconds on Unix systems.
//
// This method should not be used regularly!
// Usually, memory should stay allocated for reuse when new entities are created or
// moved between archetypes when adding or removing components.
// However, it might be useful in memory-constrained environments e.g. after initialization.
func ( *World) ( ...time.Duration) bool {
	if len() > 1 {
		panic("no more than one time limit stopAfter can be given")
	}
	 := time.Hour
	if len() > 0 {
		 = [0]
	}
	return .storage.Shrink()
}