package ecs

// Map is a mapper to access and manipulate components of an entity.
// It is equivalent to [Map1], with slightly more convenient methods tailored for a single component.
//
// Instances should be created during initialization and stored, e.g. in systems.
type Map[ any] struct {
	mask      bitMask
	world     *World
	storage   *componentStorage
	relations []relationID
	id        ID
	ids       [1]ID
	archetype archetypeID
}

// NewMap creates a new [Map].
//
// See also [Map.New] for a shortcut when constructing an already defined instance.
func [ any]( *World) *Map[] {
	 := ComponentID[]()
	return &Map[]{
		mask:    newMask(),
		world:   ,
		id:      ,
		ids:     [1]ID{},
		storage: &.storage.components[.id],
	}
}

// New creates a new [Map]. It is safe to call on `nil` instance.
// It is a helper method, intended to avoid repeated specification of the type parameter.
func (*Map[]) ( *World) *Map[] {
	return NewMap[]()
}

// NewEntity creates a new entity with the mapped component.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
func ( *Map[]) ( *,  ...Entity) Entity {
	return .NewEntityFn(func( *) {
		* = *
	}, ...)
}

// NewEntityFn creates a new entity with the mapped component and runs a callback instead of using a component for initialization.
// The callback can be nil.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
//
// ⚠️ Do not store the obtained pointer outside of the current context!
func ( *Map[]) ( func(*),  ...Entity) Entity {
	.relations = relationEntities().ToRelation(.world, .id, .relations)
	, ,  := .world.newEntity(.ids[:], .relations, .archetype)
	.archetype = 
	if  != nil {
		(.GetUnchecked())
	}
	.world.storage.observers.FireCreateEntityIfHas(, )
	if len() > 0 {
		.world.storage.observers.FireCreateEntityRelIfHas(, )
	}
	return 
}

// NewBatch creates a batch of new entities with the mapped component.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
func ( *Map[]) ( int,  *,  ...Entity) {
	.NewBatchFn(, func( Entity,  *) {
		* = *
	}, ...)
}

// NewBatchFn creates a batch of new entities with the mapped components, running the given initializer function on each.
// The initializer function can be nil.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
//
// ⚠️ Do not store the obtained pointers outside of the current context!
func ( *Map[]) ( int,  func(Entity, *),  ...Entity) {
	.world.checkLocked()
	.relations = relationEntities().ToRelation(.world, .id, .relations)
	, ,  := .world.newEntities(, .ids[:], .relations, .archetype)
	.archetype = 

	 := .world.storage.observers.HasObservers(OnCreateEntity)
	 := len() > 0 && .world.storage.observers.HasObservers(OnAddRelations)
	 :=  ||  ||  != nil
	var  uint8
	if  {
		 = .world.lock()
	}

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

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

	if  {
		 := &.world.storage.tables[]
		.world.storage.observers.FireCreateEntityRelBatch(, , &.mask)
	}

	if  {
		.world.unlock()
	}
}

// Get returns the mapped component for the given entity.
//
// Returns nil if the entity does not have the mapped component.
//
// ⚠️ Do not store the obtained pointer outside of the current context!
func ( *Map[]) ( Entity) * {
	if !.world.storage.entityPool.Alive() {
		panic("can't get a component of a dead entity")
	}
	 := &.world.storage.entities[.id]
	return get[](.storage, )
}

// GetUnchecked returns the mapped component for the given entity.
// In contrast to [Map.Get], it does not check whether the entity is alive.
// Can be used as an optimization when it is certain that the entity is alive.
//
// Returns nil if the entity does not have the mapped component.
//
// ⚠️ Do not store the obtained pointer outside of the current context!
func ( *Map[]) ( Entity) * {
	 := &.world.storage.entities[.id]
	return get[](.storage, )
}

// Has return whether the given entity has the mapped component.
//
// Using [Map.Get] and checking for nil pointer may be faster
// than calling [Map.Has] and [Map.Get] subsequently.
func ( *Map[]) ( Entity) bool {
	if !.world.storage.entityPool.Alive() {
		panic("can't get a component of a dead entity")
	}
	return .HasUnchecked()
}

// HasUnchecked return whether the given entity has the mapped component.
// In contrast to [Map.Has], it does not check whether the entity is alive.
// Can be used as an optimization when it is certain that the entity is alive.
func ( *Map[]) ( Entity) bool {
	return .storage.columns[.world.storage.entities[.id].table] != nil
}

// Add the mapped component to the given entity.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
func ( *Map[]) ( Entity,  *,  ...Entity) {
	.AddFn(, func( *) {
		* = *
	}, ...)
}

// AddFn adds the mapped component to the given entity and runs a callback instead of using a component for initialization.
// The callback can be nil.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
//
// ⚠️ Do not store the obtained pointer outside of the current context!
func ( *Map[]) ( Entity,  func(*),  ...Entity) {
	if !.world.storage.entityPool.Alive() {
		panic("can't add a component to a dead entity")
	}
	.relations = relationEntities().ToRelation(.world, .id, .relations)
	,  := .world.add(, .ids[:], .relations)
	if  != nil {
		(.GetUnchecked())
	}

	.world.storage.observers.FireAddIfHas(OnAddComponents, , , )
	if len() > 0 {
		.world.storage.observers.FireAddIfHas(OnAddRelations, , , )
	}
}

// Set the mapped component of the given entity to the given values.
// Requires the entity to already have the mapped component.
//
// Triggers an OnSetComponents event, which is not the case when assigning by
// pointer dereference or assigning to fields. This can be used to notify observers
// about component updates.
//
// This is not a component operation, so it can be performed on a locked world.
func ( *Map[]) ( Entity,  *) {
	if !.world.storage.entityPool.Alive() {
		panic("can't set component of a dead entity")
	}
	.world.storage.checkHasComponent(, .ids[0])

	 := &.world.storage.entities[.id]
	*(*)(.storage.columns[.table].Get(uintptr(.row))) = *

	if .world.storage.observers.HasObservers(OnSetComponents) {
		 := &.world.storage.archetypes[.world.storage.tables[.table].archetype].mask
		.world.storage.observers.FireSet(, &.mask, )
	}
}

// AddBatch adds the mapped component to all entities matching the given batch filter.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
func ( *Map[]) ( Batch,  *,  ...Entity) {
	.AddBatchFn(, func( Entity,  *) {
		* = *
	}, ...)
}

// AddBatchFn adds the mapped component to all entities matching the given batch filter,
// running the given function on each. The function can be nil.
//
// If the mapped component is a relationship (see [RelationMarker]),
// a relation target entity must be provided.
//
// ⚠️ Do not store the obtained pointers outside of the current context!
func ( *Map[]) ( Batch,  func(Entity, *),  ...Entity) {
	.relations = relationEntities().ToRelation(.world, .id, .relations)

	var  func( tableID, ,  uint32)
	if  != nil {
		 = func( tableID, ,  uint32) {
			 := &.world.storage.tables[]
			 := .storage.columns[]

			for  := range  {
				 := uintptr( + )
				(
					.GetEntity(),
					(*)(.Get()),
				)
			}
		}
	}
	.world.exchangeBatch(&, .ids[:], nil, .relations, )
}

// Remove the mapped component from the given entity.
func ( *Map[]) ( Entity) {
	if !.world.storage.entityPool.Alive() {
		panic("can't remove a component from a dead entity")
	}
	.world.remove(, .ids[:])
}

// RemoveBatch removes the mapped component from all entities matching the given batch filter,
// running the given function on each. The function can be nil.
func ( *Map[]) ( Batch,  func( Entity)) {
	removeBatch(.world, &, .ids[:], )
}

// GetRelation returns the relation target for the entity and the mapped component.
func ( *Map[]) ( Entity) Entity {
	return .world.storage.getRelation(, .id)
}

// GetRelationUnchecked returns the relation target for the entity and the mapped component.
// In contrast to [Map.GetRelation], it does not check whether the entity is alive.
// Can be used as an optimization when it is certain that the entity is alive.
func ( *Map[]) ( Entity) Entity {
	return .world.storage.getRelationUnchecked(, .id)
}

// SetRelation sets the relation target for the entity and the mapped component.
func ( *Map[]) ( Entity,  Entity) {
	.relations = toRelation(.world, , .id, .relations)
	.world.setRelations(, .relations)
}

// SetRelationBatch sets the relation target for all entities matching the given batch filter.
func ( *Map[]) ( Batch,  Entity,  func( Entity)) {
	.relations = toRelation(.world, , .id, .relations)
	setRelationsBatch(.world, &, , .relations)
}