package ecs

import (
	
	

	
)

// archetype ID/index type.
type archetypeID uint32

// maxArchetypeID is used as unassigned archetype ID.
const maxArchetypeID = math.MaxUint32

// archetype struct.
type archetype struct {
	*archetypeData
	componentsMap  []int16                  // mapping from component IDs to column indices; -1 indicates none
	relationTables []map[entityID]*tableIDs // lookup for relation targets of tables, indexed by column index
	tables         tableIDs                 // all active tables
	mask           bitMask                  // Bit mask for the archetype's components
	id             archetypeID              // ID of the archetype
	numRelations   uint8                    // number of relation components
}

type archetypeData struct {
	components   []ID                   // components IDs of the archetype in arbitrary order
	itemSizes    []uint32               // item size per component index
	isRelation   []bool                 // whether columns are relations components, indexed by column index
	freeTables   []tableID              // all inactive/free tables
	targetTables map[entityID]*tableIDs // all tables per target for cleanup
	node         nodeID                 // Node ID of the archetype
}

// tableIDs helper for faster search and remove operations.
type tableIDs struct {
	tables  []tableID          // List of tables
	indices map[tableID]uint32 // Mapping from table ID to the index in the list
}

// Creates a new tableIDs.
// The passed tables slice is used directly, so it should not be modified or stored afterwards.
func newTableIDs( ...tableID) tableIDs {
	 := make(map[tableID]uint32, len())
	for ,  := range  {
		[] = uint32()
	}
	return tableIDs{
		tables:  ,
		indices: ,
	}
}

// Append a table ID.
func ( *tableIDs) ( tableID) {
	.tables = append(.tables, )
	.indices[] = uint32(len(.tables) - 1)
}

// Remove a table ID.
func ( *tableIDs) ( tableID) bool {
	,  := .indices[]
	if ! {
		return false
	}

	 := uint32(len(.tables) - 1)
	if  !=  {
		.tables[], .tables[] = .tables[], .tables[]
		.indices[.tables[]] = 
	}
	.tables = .tables[:]
	delete(.indices, )

	return true
}

// Clear the list and the mapping.
func ( *tableIDs) () {
	.tables = .tables[:0]
	.indices = map[tableID]uint32{}
}

// newArchetype creates a new archetype.
func newArchetype(
	 archetypeID,  nodeID,  *bitMask,
	 []ID,  []tableID,  *componentRegistry) (archetype, archetypeData) {
	 := make([]int16, maskTotalBits)
	for  := range maskTotalBits {
		[] = -1
	}

	 := make([]uint32, len())
	for ,  := range  {
		[.id] = int16()
		 := .Types[.id]

		 := .Size()
		[] = uint32()
	}

	 := uint8(0)
	 := make([]bool, len())
	 := make([]map[entityID]*tableIDs, len())
	for ,  := range  {
		if .IsRelation[.id] {
			[] = true
			[] = map[entityID]*tableIDs{}
			++
		}
	}
	var  map[entityID]*tableIDs
	if  > 0 {
		 = map[entityID]*tableIDs{}
	}
	 := newTableIDs(...)
	return archetype{
			id:             ,
			mask:           *,
			componentsMap:  ,
			tables:         ,
			numRelations:   ,
			relationTables: ,
		}, archetypeData{
			node:         ,
			components:   ,
			targetTables: ,
			itemSizes:    ,
			isRelation:   ,
		}
}

// HasRelations returns whether the archetype has any relation components.
func ( *archetype) () bool {
	return .numRelations > 0
}

// GetTable returns the table that matches the given relations exactly,
// and whether there is a matching table.
//
// Relations must be fully specified.
func ( *archetype) ( *storage,  []relationID) (*table, bool) {
	if len(.tables.tables) == 0 {
		return nil, false
	}
	if !.HasRelations() {
		return &.tables[.tables.tables[0]], true
	}
	return .getTableSlowPath(, )
}

// slow path for GetTable for archetypes with relations.
func ( *archetype) ( *storage,  []relationID) (*table, bool) {
	if uint8(len()) < .numRelations {
		panic("relation targets must be fully specified")
	}
	 := .componentsMap[[0].component.id]
	,  := .relationTables[][[0].target.id]
	if ! {
		return nil, false
	}
	for ,  := range .tables {
		 := &.tables[]
		if .MatchesExact() {
			return , true
		}
	}
	return nil, false
}

// GetTables return all tables matching the first given relation, if any.
// Otherwise, returns all tables of the archetype.
//
// Relations do not need to be fully specified.
func ( *archetype) ( []relationID) []tableID {
	if !.HasRelations() || len() == 0 {
		return .tables.tables
	}
	 := .componentsMap[[0].component.id]
	if ,  := .relationTables[][[0].target.id];  {
		return .tables
	}
	return nil
}

// GetFreeTable returns a free/unused table ID of the archetype,
// and whether there is any free table.
func ( *archetype) () (tableID, bool) {
	if len(.freeTables) == 0 {
		return 0, false
	}
	 := len(.freeTables) - 1
	 := .freeTables[]

	.freeTables = .freeTables[:]

	return , true
}

// FreeTable frees the given table.
//
// Removes the table from the archetype's list of tables
// and from the archetype's relation tables.
//
// Does not clear the table's content.
func ( *archetype) ( *table) {
	_ = .tables.Remove(.id)
	.freeTables = append(.freeTables, .id)
	.isFree = true

	// If there is only one relation, the resp. relationTables
	// entry is removed anyway.
	if .numRelations <= 1 {
		return
	}

	// TODO: can/should we be more selective here?
	// For a potential solution, see https://github.com/mlange-42/ark/pull/264
	for ,  := range .relationTables {
		for ,  := range  {
			_ = .Remove(.id)
		}
	}
	for ,  := range .targetTables {
		_ = .Remove(.id)
	}
}

// FreeAllTables frees all tables of the archetype.
//
// Does not clear the tables' contents.
func ( *archetype) ( *storage) {
	for ,  := range .tables.tables {
		.tables[].isFree = true
	}
	.freeTables = append(.freeTables, .tables.tables...)
	.tables.Clear()

	for  := range .relationTables {
		.relationTables[] = map[entityID]*tableIDs{}
	}
	.targetTables = map[entityID]*tableIDs{}
}

// AddTable adds the given table to the archetype's list of tables,
// and to the relation tables of there are any relations.
func ( *archetype) ( *table) {
	.tables.Append(.id)
	if !.HasRelations() {
		return
	}

	for  := range .ids {
		 := &.columns[]
		if !.isRelation {
			continue
		}
		 := .target
		 := .relationTables[]

		if ,  := [.id];  {
			.Append(.id)
		} else {
			 := newTableIDs(.id)
			[.id] = &
		}

		if ,  := .targetTables[.id];  {
			if ,  := .indices[.id]; ! {
				.Append(.id)
			}
		} else {
			 := newTableIDs(.id)
			.targetTables[.id] = &
		}
	}
}

// RemoveTarget removes a relation target entity from the archetype's relation tables.
func ( *archetype) ( Entity) {
	for  := range .relationTables {
		if !.isRelation[] {
			continue
		}
		delete(.relationTables[], .id)
	}
	delete(.targetTables, .id)
}

// Reset the archetype. Clears and frees all tables.
func ( *archetype) ( *storage) {
	if !.HasRelations() {
		.tables[.tables.tables[0]].Reset()
		return
	}

	for  := len(.tables.tables) - 1;  >= 0; -- {
		 := &.tables[.tables.tables[]]
		.Reset()
	}

	.FreeAllTables()
}

// Stats generates statistics for an archetype.
func ( *archetype) ( *storage) stats.Archetype {
	 := .components
	 := make([]reflect.Type, len())
	 := make([]string, len())
	for ,  := range  {
		,  := .registry.ComponentType(.id)
		[] = 
		[] = .Name()
	}

	 := int(entitySize)
	 := make([]uint8, len())
	for ,  := range  {
		[] = .id
		 += int(.itemSizes[])
	}

	 := 0
	 := 0
	 := 0
	 := 0
	 := make([]stats.Table, len(.tables.tables))
	for ,  := range .tables.tables {
		 := &.tables[]
		[] = .Stats()
		 := &[]
		 += .Capacity
		 += .Size
		 += .Memory
		 += .MemoryUsed
	}
	for ,  := range .freeTables {
		 := &.tables[]
		 += int(.cap)
		 +=  * int(.cap)
	}

	return stats.Archetype{
		FreeTables:         len(.freeTables),
		NumRelations:       int(.numRelations),
		ComponentIDs:       ,
		ComponentTypes:     ,
		ComponentTypeNames: ,
		Memory:             ,
		MemoryUsed:         ,
		MemoryPerEntity:    ,
		Size:               ,
		Capacity:           ,
		Tables:             ,
	}
}

// UpdateStats updates statistics for an archetype.
func ( *archetype) ( *stats.Archetype,  *storage) {
	 := .tables

	 := 0
	 := 0
	 := 0
	 := 0

	 := int32(len(.Tables))
	 := int32(len(.tables))
	if  <  {
		.Tables = .Tables[:]
		 = 
	}
	var  int32
	for  := range  {
		 := &.Tables[]
		 := &.tables[.tables[]]
		.UpdateStats(.MemoryPerEntity, )
		 += .Capacity
		 += .Size
		 += .Memory
		 += .MemoryUsed
	}
	for  = ;  < ; ++ {
		 := &.tables[.tables[]]
		 := .Stats(.MemoryPerEntity)
		.Tables = append(.Tables, )
		 += .Capacity
		 += .Size
		 += .Memory
		 += .MemoryUsed
	}
	for ,  := range .freeTables {
		 := &.tables[]
		 += int(.cap)
		 += .MemoryPerEntity * int(.cap)
	}

	.FreeTables = len(.freeTables)
	.Capacity = 
	.Size = 
	.Memory = 
	.MemoryUsed = 
}