package ecs

// UnsafeQuery is an unsafe query.
// It is significantly slower than type-safe generic queries like [Query2],
// and should only be used when component types are not known at compile time.
type UnsafeQuery struct {
	world     *World
	table     *table
	relations []relationID
	tables    []tableID
	filter    filter
	cursor    cursor
	lock      uint8
}

// Has returns whether the current entity has the given component.
func ( *UnsafeQuery) ( ID) bool {
	return .table.Has()
}

// GetRelation returns the entity relation target of the component at the given index.
func ( *UnsafeQuery) ( ID) Entity {
	return .table.GetRelation()
}

// Count returns the number of entities matching this query.
func ( *UnsafeQuery) () int {
	return countQuery(&.world.storage, &.filter, .relations, .world.storage.allArchetypes)
}

// EntityAt returns the entity at a given index.
//
// The method is particularly useful for random sampling of entities from a query.
// However, performance depends on the number of archetypes in the world and in the query.
// In worlds with many archetypes, it is recommended to use a registered/cached filter.
//
// Do not use this to iterate a query! Use [Query.Next] instead.
//
// Panics if the index is out of range, as indicated by [Query.Count].
func ( *UnsafeQuery) ( int) Entity {
	return entityAt(&.world.storage, &.filter, .relations, .world.storage.allArchetypes, uint32())
}

// IDs returns the IDs of all component of the current [Entity]n.
func ( *UnsafeQuery) () IDs {
	return newIDs(.table.ids)
}

// Close closes the Query and unlocks the world.
//
// Automatically called when iteration completes.
// Needs to be called only if breaking out of the query iteration or not iterating at all.
func ( *UnsafeQuery) () {
	if .cursor.table < -1 {
		return
	}
	.cursor.archetype = -2
	.cursor.table = -2
	.tables = nil
	.table = nil
	.world.unlockSafe(.lock)
}

func ( *UnsafeQuery) () bool {
	if .cursor.archetype >= 0 && .nextTable() {
		return true
	}
	return .nextArchetype()
}

func ( *UnsafeQuery) () bool {
	.tables = nil
	 := int32(len(.world.storage.archetypes) - 1)
	for .cursor.archetype <  {
		.cursor.archetype++
		 := &.world.storage.archetypes[.cursor.archetype]
		if !.filter.matches(&.mask) {
			continue
		}

		if !.HasRelations() {
			 := &.world.storage.tables[.tables.tables[0]]
			if .len > 0 {
				.setTable(0, )
				return true
			}
			continue
		}

		.tables = .GetTables(.relations)
		.cursor.table = -1
		if .nextTable() {
			return true
		}
	}
	.Close()
	return false
}

func ( *UnsafeQuery) () bool {
	 := int32(len(.tables) - 1)
	for .cursor.table <  {
		.cursor.table++
		 := &.world.storage.tables[.tables[.cursor.table]]
		if .len == 0 || !.Matches(.relations) {
			continue
		}
		.setTable(.cursor.table, )
		return true
	}
	return false
}

func ( *UnsafeQuery) ( int32,  *table) {
	.cursor.table = 
	.table = 
	.cursor.index = 0
	.cursor.maxIndex = int64(.table.len - 1)
}