package ecs

import 

// Unsafe provides access to Ark's unsafe ID-based API.
// Get an instance via [World.Unsafe].
//
// The unsafe API is significantly slower than the type-safe API,
// and should only be used when component types are not known at compile time.
type Unsafe struct {
	world           *World
	cachedRelations []relationID
}

// NewEntity creates a new entity with the given components.
func ( Unsafe) ( ...ID) Entity {
	, ,  := .world.newEntity(, nil, 0)
	.world.storage.observers.FireCreateEntityIfHas(, )
	return 
}

// NewEntityRel creates a new entity with the given components and relation targets.
func ( Unsafe) ( []ID,  ...Relation) Entity {
	.cachedRelations = relationSlice().ToRelationIDsForUnsafe(.world, .cachedRelations[:0])
	, ,  := .world.newEntity(, .cachedRelations, 0)
	.world.storage.observers.FireCreateEntityIfHas(, )
	if len() > 0 {
		.world.storage.observers.FireCreateEntityRelIfHas(, )
	}
	return 
}

// Get returns a pointer to the given component of an [Entity].
//
// ⚠️ Do not store the obtained pointer outside of the current context!
//
// Panics if the entity does not have the given component.
// Panics when called for a removed (and potentially recycled) entity.
func ( Unsafe) ( Entity,  ID) unsafe.Pointer {
	return .world.storage.get(, )
}

// GetUnchecked returns a pointer to the given component of an [Entity].
// In contrast to [Unsafe.Get], it does not check whether the entity is alive.
//
// ⚠️ Do not store the obtained pointer outside of the current context!
//
// Panics if the entity does not have the given component.
func ( Unsafe) ( Entity,  ID) unsafe.Pointer {
	return .world.storage.getUnchecked(, )
}

// Has returns whether an [Entity] has the given component.
//
// Panics when called for a removed (and potentially recycled) entity.
func ( Unsafe) ( Entity,  ID) bool {
	return .world.storage.has(, )
}

// HasUnchecked returns whether an [Entity] has the given component.
// In contrast to [Unsafe.Has], it does not check whether the entity is alive.
//
// Panics when called for a removed (and potentially recycled) entity.
func ( Unsafe) ( Entity,  ID) bool {
	return .world.storage.hasUnchecked(, )
}

// GetRelation returns the relation target for the entity and the mapped component.
func ( Unsafe) ( Entity,  ID) Entity {
	return .world.storage.getRelation(, )
}

// GetRelationUnchecked returns the relation target for the entity and the mapped component.
// In contrast to [Unsafe.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 ( Unsafe) ( Entity,  ID) Entity {
	return .world.storage.getRelationUnchecked(, )
}

// SetRelations sets relation targets for an entity.
func ( Unsafe) ( Entity,  ...Relation) {
	.cachedRelations = relationSlice().ToRelationIDsForUnsafe(.world, .cachedRelations[:0])
	.world.setRelations(, .cachedRelations)
}

// Add the given components to an entity.
func ( Unsafe) ( Entity,  ...ID) {
	if !.world.Alive() {
		panic("can't add components to a dead entity")
	}
	,  := .world.add(, , nil)
	.world.storage.observers.FireAddIfHas(OnAddComponents, , , )
}

// AddRel adds the given components and relation targets to an entity.
func ( Unsafe) ( Entity,  []ID,  ...Relation) {
	if !.world.Alive() {
		panic("can't add components to a dead entity")
	}
	.cachedRelations = relationSlice().ToRelationIDsForUnsafe(.world, .cachedRelations[:0])
	,  := .world.add(, , .cachedRelations)
	.world.storage.observers.FireAddIfHas(OnAddComponents, , , )
	if len() > 0 {
		.world.storage.observers.FireAddIfHas(OnAddRelations, , , )
	}
}

// Remove the given components from an entity.
func ( Unsafe) ( Entity,  ...ID) {
	if !.world.Alive() {
		panic("can't remove components from a dead entity")
	}
	.world.remove(, )
}

// Exchange the given components on entity.
func ( Unsafe) ( Entity,  []ID,  []ID,  ...Relation) {
	if !.world.Alive() {
		panic("can't exchange components on a dead entity")
	}
	.cachedRelations = relationSlice().ToRelationIDsForUnsafe(.world, .cachedRelations[:0])
	,  := .world.exchange(, , , .cachedRelations)

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

// IDs returns all component IDs of an entity.
func ( Unsafe) ( Entity) IDs {
	if !.world.Alive() {
		panic("can't get component IDs of a dead entity")
	}
	 := .world.storage.entities[.id]
	return newIDs(.world.storage.tables[.table].ids)
}

// DumpEntities dumps entity information into an [EntityDump] object.
// This dump can be used with [Unsafe.LoadEntities] to set the World's entity state.
//
// For world serialization with components and resources, see module [github.com/mlange-42/ark-serde].
func ( Unsafe) () EntityDump {
	 := NewFilter0(.world)
	 := .Query()
	 := make([]uint32, 0, .Count())
	for .Next() {
		 = append(, uint32(.Entity().id))
	}

	 := EntityDump{
		Entities:  append([]Entity{}, .world.storage.entityPool.entities...),
		Alive:     ,
		Next:      uint32(.world.storage.entityPool.next),
		Available: .world.storage.entityPool.available,
	}

	return 
}

// LoadEntities resets all entities to the state saved with [Unsafe.DumpEntities].
//
// Use this only on an empty world! Can be used after [World.Reset].
//
// The resulting world will have the same entities (in terms of ID, generation and alive state)
// as the original world. This is necessary for proper serialization of entity relations.
// However, the entities will not have any components.
//
// Panics if the world has any dead or alive entities.
//
// For world serialization with components and resources, see module [github.com/mlange-42/ark-serde].
func ( Unsafe) ( *EntityDump) {
	.world.checkLocked()

	if len(.world.storage.entityPool.entities) > 2 || .world.storage.entityPool.available > 0 {
		panic("can set entity data only on a fresh or reset world")
	}

	 := len(.Entities)

	 := make([]Entity, )
	copy(, .Entities)

	if  > 0 {
		.world.storage.entityPool = entityPool{
			entities:  ,
			next:      entityID(.Next),
			available: .Available,
			reserved:  entityID(reservedEntities),
		}
		.world.storage.entityPool.pointer = unsafe.Pointer(&.world.storage.entityPool.entities[0])
	}

	.world.storage.entities = make([]entityIndex, )
	.world.storage.isTarget = make([]bool, )

	 := &.world.storage.tables[0]
	.Extend(uint32(len(.Alive)))
	for ,  := range .Alive {
		 := .world.storage.entityPool.entities[]
		 := .Add()
		.world.storage.entities[.id] = entityIndex{table: .id, row: }
	}
}