import { ResourceDescriptor, Mut, CommandsDescriptor, Memory, QueryDescriptor, With } from 'thyseus';
import { Warehouse } from "@houseki-engine/core";
import { Geometry, GlobalTransform, LineMaterial, Mesh, MeshMode, Parent, SceneStruct, Transform, } from "@houseki-engine/scene";
import { Commands, Entity, Mut, Query, Res, With } from "thyseus";
import { DebugResource, PhysicsConfig, PhysicsStore } from "../resources";
export function generateDebug(warehouse: Res<Mut<Warehouse>>, commands: Commands, debug: Res<Mut<DebugResource>>, physicsStore: Res<PhysicsStore>, physicsConfig: Res<PhysicsConfig>, sceneStruct: Res<SceneStruct>, meshes: Query<[
    Entity,
    Mut<Geometry>,
    Mut<Parent>
], With<LineMaterial>>) {
    debug.deserialize();
    physicsConfig.deserialize();
    sceneStruct.deserialize();
    if (!physicsConfig.debug) {
        // Remove the debug lines if they exist
        if (debug.linesId) {
            commands.despawnById(debug.linesId);
            debug.linesId = 0n;
        }
        // @ts-expect-error
        debug.serialize();
        return;
    }
    const buffers = physicsStore.world.debugRender();
    let linesFound = false;
    if (!debug.linesId) {
        linesFound = true;
        const material = new LineMaterial();
        material.vertexColors = true;
        const mesh = new Mesh();
        mesh.mode = MeshMode.LINES;
        mesh.frustumCulled = false;
        const parent = new Parent(sceneStruct.activeScene);
        const linesId = commands
            .spawn(true)
            .add(material)
            .addType(Geometry)
            .add(mesh)
            .addType(Transform)
            .addType(GlobalTransform)
            .add(parent).id;
        debug.linesId = linesId;
    }
    for (const [entity, geometry, parent] of meshes) {
        entity.deserialize();
        geometry.deserialize();
        parent.deserialize();
        if (entity.id !== debug.linesId)
            continue;
        linesFound = true;
        parent.id = sceneStruct.activeScene;
        geometry.positions.write(buffers.vertices, warehouse);
        geometry.colors.write(buffers.colors, warehouse);
        entity.serialize();
        geometry.serialize();
        parent.serialize();
    }
    if (!linesFound && debug.linesId) {
        commands.despawnById(debug.linesId);
        debug.linesId = 0n;
    }
    debug.serialize();
    physicsConfig.serialize();
    sceneStruct.serialize();
}
generateDebug.parameters = [new ResourceDescriptor(new Mut(Warehouse)), new CommandsDescriptor(), new ResourceDescriptor(new Mut(DebugResource)), new ResourceDescriptor(PhysicsStore), new ResourceDescriptor(PhysicsConfig), new ResourceDescriptor(SceneStruct), new QueryDescriptor([Entity, new Mut(Geometry), new Mut(Parent)], new With(LineMaterial))];
