import { Transform, RendererAPI, } from 'dacha';
import { v4 as uuidv4 } from 'uuid';
import { getGridValue, getGridStep, } from '../../../utils/grid';
import { getTool } from '../../../utils/get-tool';
import { getUniqueName } from '../../../utils/get-unique-name';
import { TOOL_NAME, SCENE_PATH_LEGTH } from './consts';
const buildActor = (template, actors) => {
    var _a;
    return ({
        id: uuidv4(),
        templateId: template.id,
        name: actors ? getUniqueName(template.name, actors) : template.name,
        components: [],
        children: ((_a = template.children) !== null && _a !== void 0 ? _a : []).map((child) => buildActor(child)),
    });
};
export const createFromTemplate = (template, actors, x, y) => {
    var _a, _b;
    const templateCopy = structuredClone(template);
    const actor = buildActor(templateCopy, actors);
    const transform = (_a = templateCopy.components) === null || _a === void 0 ? void 0 : _a.find((component) => component.name === Transform.componentName);
    if (transform !== undefined) {
        transform.config.offsetX = x;
        transform.config.offsetY = y;
        (_b = actor.components) === null || _b === void 0 ? void 0 : _b.push(transform);
    }
    return actor;
};
export const updatePreviewPosition = (cursor, world, preview) => {
    if (cursor.x === null || cursor.y === null) {
        return;
    }
    const tool = getTool(world);
    const gridStep = getGridStep(world);
    if (tool.name !== TOOL_NAME) {
        return;
    }
    const templateId = tool.features.templateId.value;
    const snapToGrid = tool.features.grid.value;
    if (templateId === undefined) {
        return;
    }
    const transform = preview === null || preview === void 0 ? void 0 : preview.getComponent(Transform);
    if (!preview || !transform) {
        return;
    }
    if (!snapToGrid) {
        transform.world.position.x = Math.round(cursor.x);
        transform.world.position.y = Math.round(cursor.y);
        return;
    }
    const rendererApi = world.systemApi.get(RendererAPI);
    const bounds = rendererApi.getBounds(preview);
    if (!bounds) {
        return;
    }
    transform.world.position.x = getGridValue(cursor.x, bounds.width, gridStep);
    transform.world.position.y = getGridValue(cursor.y, bounds.height, gridStep);
};
export const isActorPath = (path) => path !== undefined && path[0] === 'scenes' && path.length > SCENE_PATH_LEGTH;
