package ecs

// UnsafeFilter is a filter for components.
//
// It is significantly slower than type-safe generic filters like [Filter2],
// and should only be used when component types are not known at compile time.
type UnsafeFilter struct {
	filter
	world *World
}

// NewUnsafeFilter creates a new [UnsafeFilter] matching the given components.
func ( *World,  ...ID) UnsafeFilter {
	return UnsafeFilter{
		world:  ,
		filter: newFilter(...),
	}
}

// Without specifies components to exclude.
// Resets previous excludes.
func ( UnsafeFilter) ( ...ID) UnsafeFilter {
	if len() == 0 {
		return 
	}
	.filter = .filter.Without(...)
	return 
}

// Exclusive makes the filter exclusive in the sense that the component composition is matched exactly,
// and no other components are allowed.
//
// Overwrites components set via [Filter.Without].
func ( UnsafeFilter) () UnsafeFilter {
	.filter = .filter.Exclusive()
	return 
}

// Query returns a new query matching this filter and the given entity relation targets.
func ( UnsafeFilter) ( ...Relation) UnsafeQuery {
	 := relationSlice().ToRelationIDsForUnsafe(.world, nil)
	return UnsafeQuery{
		world:     .world,
		filter:    .filter,
		relations: ,
		lock:      .world.lockSafe(),
		cursor: cursor{
			archetype: -1,
			table:     -1,
			index:     0,
			maxIndex:  -1,
		},
	}
}

// filter is an mask filter for component presence and optional absence.
type filter struct {
	mask       bitMask
	without    bitMask
	cache      cacheID
	hasWithout bool
}

// newFilter creates a new filter for presence of the given components.
func newFilter( ...ID) filter {
	return filter{
		mask:  newMask(...),
		cache: maxCacheID,
	}
}

// matches this filter against a (archetype) mask.
func ( *filter) ( *bitMask) bool {
	return .Contains(&.mask) && (!.hasWithout || !.ContainsAny(&.without))
}

// Without specifies components to exclude.
// Resets previous excludes.
func ( filter) ( ...ID) filter {
	.without = newMask(...)
	.hasWithout = true
	return 
}

// Exclusive makes the filter exclusive in the sense that the component composition is matched exactly,
// and no other components are allowed.
func ( filter) () filter {
	.without = .mask.Not()
	.hasWithout = true
	return 
}