package ecs

import (
	
	
	
	

	
)

// tableID is the type of table IDs.
type tableID uint32

// maxTableID is used as table ID for unused entities.
const maxTableID = math.MaxUint32

// table stores entities and components of an archetype,
// or of a certain combination of relations inside an archetype.
type table struct {
	entities    entityColumn // column for entities
	components  []*column    // mapping from component IDs to columns
	ids         []ID         // components IDs in the same order as in the archetype
	columns     []column     // columns in dense order
	relationIDs []relationID // all relation IDs and targets of the table
	id          tableID      // ID of the table
	archetype   archetypeID  // ID of the table's archetype
	len         uint32       // length of the table (number of rows)
	cap         uint32       // capacity of the table (number of rows)
	isFree      bool         // Whether the table is currently free
}

// newTable creates a new table.
func newTable( tableID,  *archetype,  uint32,  *componentRegistry,  []Entity,  []relationID) table {
	 := newEntityColumn()
	 := make([]column, len(.components))

	 := make([]*column, maskTotalBits)
	for ,  := range .components {
		 := uintptr(.itemSizes[])
		[] = newColumn(uint32(), .Types[.id], , .isRelation[], .IsTrivial[.id], [], )
		[.id] = &[]
	}

	return table{
		id:          ,
		archetype:   .id,
		components:  ,
		entities:    ,
		ids:         .components,
		columns:     ,
		relationIDs: ,
		cap:         ,
	}
}

// Recycle the table, using the given relations and targets, indexed by column index.
func ( *table) ( []Entity,  []relationID) {
	.relationIDs = 
	for  := range .columns {
		.columns[].target = []
	}
	.isFree = false
}

// HasRelations returns whether the table contains any relation components.
func ( *table) () bool {
	return len(.relationIDs) > 0
}

// Add an entity to the table.
// Returns the entity's new row index.
func ( *table) ( Entity) uint32 {
	 := .len
	.Alloc(1)
	.entities.Set(, unsafe.Pointer(&))
	return 
}

// Get a pointer to the given component at the given index.
func ( *table) ( ID,  uintptr) unsafe.Pointer {
	return .components[.id].Get()
}

// Has returns whether the table has a column for the given component.
func ( *table) ( ID) bool {
	return .components[.id] != nil
}

// GetEntity returns the entity at the given row index.
func ( *table) ( uintptr) Entity {
	return *(*Entity)(.entities.Get())
}

// GetRelation returns the target entity for the given relation component.
func ( *table) ( ID) Entity {
	return .components[.id].target
}

// Column returns the column pointer for the given component ID.
func ( *table) ( ID) *column {
	return .components[.id]
}

// Set the value of a component at the given row index from a column from another table.
func ( *table) ( ID,  uint32,  *column,  uint32) {
	.components[.id].Set(, , )
}

// CopyAll copies all component values from a row of another table with the same layout into this table.
func ( *table) ( *table,  uint32,  uint32) {
	for  := range .columns {
		.columns[].Set(, &.columns[], )
	}
}

// SetEntity sets the entity at the given row index.
func ( *table) ( uint32,  Entity) {
	.entities.Set(, unsafe.Pointer(&))
}

// Alloc allocates memory for the given number of entities.
func ( *table) ( uint32) {
	.Extend()
	.len += 
}

// Extend the table to be able to store the given number of additional entities.
// Has no effect if the table's capacity is already sufficient.
// If the capacity needs to be increased, it will be doubled until it is sufficient.
func ( *table) ( uint32) {
	 := .len + 
	if .cap >=  {
		return
	}
	.adjustCapacity(capPow2())
}

// CanShrink returns whether the table's capacity exceeds the next power-of-2 of what is required.
func ( *table) ( uint32) bool {
	 := max(capPow2(.len), )
	return .cap > 
}

// Shrink the table's capacity to the next power-of-2 of what is required.
func ( *table) ( uint32) bool {
	 := max(capPow2(.len), )
	if .cap <=  {
		return false
	}
	.adjustCapacity()
	return true
}

// adjustCapacity changes the capacity of all columns.
// Does not check whether the change is necessary or feasible.
func ( *table) ( uint32) {
	// TODO: find a more clean way to update pointers in the storage.
	.cap = 

	.entities.data = reflect.MakeSlice(reflect.SliceOf(entityType), int(.cap), int(.cap))

	 := .entities.data.Index(0).Addr().UnsafePointer()
	if .len > 0 {
		copyPtr(.entities.pointer, , uintptr(.len)*entitySize)
	}
	.entities.pointer = 

	for  := range .columns {
		 := &.columns[]
		 := .data
		.data = reflect.MakeSlice(reflect.SliceOf(.elemType), int(.cap), int(.cap))
		if .isTrivial {
			 := .data.Index(0).Addr().UnsafePointer()
			if .len > 0 {
				copyPtr(.pointer, , uintptr(.len)*.itemSize)
			}
			.pointer = 
		} else {
			.pointer = .data.Index(0).Addr().UnsafePointer()
			if .len > 0 {
				// TODO: use typedmemmove?
				reflect.Copy(.data, )
			}
		}
	}
}

// Remove swap-removes the entity at the given index.
// Returns whether a swap was necessary.
func ( *table) ( uint32) bool {
	 := uintptr(.len - 1)
	 :=  != uint32()

	if  {
		.swapEntity(, )
		.removeColumnsSwapped(, )
	} else {
		.zeroAllColumns()
	}

	.len--
	return 
}

func ( *table) ( uint32,  uintptr) {
	 := entitySize
	 := unsafe.Add(.entities.pointer, *)
	 := unsafe.Add(.entities.pointer, uintptr()*)
	copyPtr(, , )
}

func ( *table) ( uint32,  uintptr) {
	for  := range .columns {
		 := &.columns[]

		if .isTrivial {
			 := .itemSize
			 := unsafe.Add(.pointer, *)
			 := unsafe.Add(.pointer, uintptr()*)
			copyPtr(, , )
			.Zero()
			continue
		}

		copyValue(, , , uintptr())
		.Zero()
	}
}

func ( *table) ( uintptr) {
	for  := range .columns {
		.columns[].Zero()
	}
}

// Reset the table.
// Clears all columns and sets the number of rows to zero.
func ( *table) () {
	for  := range .columns {
		.columns[].Reset(.len)
	}
	.len = 0
}

// AddAll adds all entities with components from another table with the same layout to this table.
func ( *table) ( *table,  uint32) {
	.Alloc()
	.entities.CopyToEnd(&.entities, .len, )
	for  := range .columns {
		.columns[].CopyToEnd(&.columns[], .len, )
	}
}

// AddAllEntities adds all entities (without components) from another table to this table.
func ( *table) ( *table,  uint32) {
	.Alloc()
	.entities.CopyToEnd(&.entities, .len, )
}

// MatchesExact returns whether this table matches the given relations exactly and exhaustively.
// Unspecified relations are not allowed.
func ( *table) ( []relationID) bool {
	if len() < len(.relationIDs) {
		panic("relation targets must be fully specified")
	}
	for ,  := range  {
		 := .components[.component.id]
		if  == nil {
			// TODO: is there a check anywhere that prevents adding/setting relations
			// on columns not in the table?
			continue
		}
		if !.isRelation {
			panic(fmt.Sprintf("component %d is not a relation component", .component.id))
		}
		//if rel.target == wildcard {
		//	panic("relation targets must be fully specified, no wildcard allowed")
		//}
		if .target != .target {
			return false
		}
	}
	return true
}

// Matches returns whether this table matches the given relations.
// Unspecified relations are allowed.
func ( *table) ( []relationID) bool {
	if len() == 0 || !.HasRelations() {
		return true
	}
	return .matchesRelations()
}

func ( *table) ( []relationID) bool {
	for ,  := range  {
		//if rel.target == wildcard {
		//	continue
		//}
		if .target != .components[.component.id].target {
			return false
		}
	}
	return true
}

// Len returns the length of the table (number of rows).
func ( *table) () int {
	return int(.len)
}

// Stats generates statistics for a table.
func ( *table) ( int) stats.Table {
	 := int(.cap)

	return stats.Table{
		Size:       .Len(),
		Capacity:   ,
		Memory:      * ,
		MemoryUsed: .Len() * ,
	}
}

// UpdateStats updates statistics for a table.
func ( *table) ( int,  *stats.Table) {
	 := int(.cap)

	.Size = .Len()
	.Capacity = 
	.Memory =  * 
	.MemoryUsed = .Len() * 
}