"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlignmentControls = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const remotion_1 = require("remotion");
const client_id_1 = require("../../helpers/client-id");
const align_bottom_1 = require("../../icons/align-bottom");
const align_center_horizontal_1 = require("../../icons/align-center-horizontal");
const align_center_vertical_1 = require("../../icons/align-center-vertical");
const align_left_1 = require("../../icons/align-left");
const align_right_1 = require("../../icons/align-right");
const align_top_1 = require("../../icons/align-top");
const InlineAction_1 = require("../InlineAction");
const InspectorPanelLayout_1 = require("../InspectorPanelLayout");
const selected_outline_drag_1 = require("../selected-outline-drag");
const selected_outline_types_1 = require("../selected-outline-types");
const call_add_keyframe_1 = require("../Timeline/call-add-keyframe");
const save_sequence_prop_1 = require("../Timeline/save-sequence-prop");
const timeline_translate_utils_1 = require("../Timeline/timeline-translate-utils");
const alignment_controls_1 = require("./alignment-controls");
const isPropStatusDraggable = (propStatus) => {
    return (!propStatus ||
        propStatus.status === 'static' ||
        (propStatus.status === 'keyframed' &&
            propStatus.interpolationFunction === 'interpolate'));
};
const container = {
    display: 'flex',
    flexDirection: 'row',
    gap: 4,
    padding: `0 ${InspectorPanelLayout_1.INSPECTOR_PANEL_HORIZONTAL_PADDING}px 12px`,
    alignItems: 'center',
};
const iconStyle = {
    width: 16,
    height: 16,
};
const verticalDivider = {
    width: 1,
    height: 16,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    margin: '0 8px',
};
const AlignmentButton = ({ onClick, title, Icon, disabled }) => {
    return (jsx_runtime_1.jsx(InlineAction_1.InlineAction, { title: title, onClick: onClick, renderAction: (color) => jsx_runtime_1.jsx(Icon, { style: iconStyle, color: color }), disabled: disabled }));
};
const AlignmentControls = ({ track }) => {
    var _a;
    const { previewServerState } = (0, react_1.useContext)(client_id_1.StudioServerConnectionCtx);
    const { propStatuses } = (0, react_1.useContext)(remotion_1.Internals.VisualModePropStatusesContext);
    const { getDragOverrides } = (0, react_1.useContext)(remotion_1.Internals.VisualModeDragOverridesContext);
    const { setPropStatuses } = (0, react_1.useContext)(remotion_1.Internals.VisualModeSettersContext);
    const { canvasContent, compositions } = (0, react_1.useContext)(remotion_1.Internals.CompositionManager);
    const currentCompositionMetadata = (0, react_1.useMemo)(() => {
        var _a;
        if ((canvasContent === null || canvasContent === void 0 ? void 0 : canvasContent.type) !== 'composition')
            return null;
        return ((_a = compositions.find((c) => c.id === canvasContent.compositionId)) !== null && _a !== void 0 ? _a : null);
    }, [canvasContent, compositions]);
    const timelinePosition = remotion_1.Internals.Timeline.useTimelinePosition();
    const handleAlign = (0, react_1.useCallback)((direction) => {
        var _a;
        var _b, _c, _d, _e;
        if (previewServerState.type !== 'connected' ||
            !track.nodePathInfo ||
            !track.sequence.controls) {
            return;
        }
        const ref = (_a = track.sequence.refForOutline) === null || _a === void 0 ? void 0 : _a.current;
        if (!ref) {
            return;
        }
        const nodePath = track.nodePathInfo.sequenceSubscriptionKey;
        const nodePropStatuses = remotion_1.Internals.getPropStatusesCtx(propStatuses, nodePath);
        const sourceFrame = timelinePosition - track.keyframeDisplayOffset;
        const dragOverrides = (_b = getDragOverrides(nodePath)) !== null && _b !== void 0 ? _b : {};
        const activeSchema = (0, selected_outline_drag_1.getSelectedOutlineActiveSchema)({
            schema: track.sequence.controls.schema,
            currentRuntimeValueDotNotation: track.sequence.controls.currentRuntimeValueDotNotation,
            dragOverrides,
            propStatus: nodePropStatuses,
            frame: sourceFrame,
        });
        const fieldSchema = activeSchema === null || activeSchema === void 0 ? void 0 : activeSchema[selected_outline_types_1.translateFieldKey];
        const propStatus = nodePropStatuses === null || nodePropStatuses === void 0 ? void 0 : nodePropStatuses[selected_outline_types_1.translateFieldKey];
        if ((fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema.type) !== 'translate') {
            return;
        }
        if (!isPropStatusDraggable(propStatus)) {
            return;
        }
        let elementRect;
        try {
            elementRect = ref.getBoundingClientRect();
        }
        catch (_f) {
            return;
        }
        if (!(currentCompositionMetadata === null || currentCompositionMetadata === void 0 ? void 0 : currentCompositionMetadata.width)) {
            return;
        }
        const compositionRect = remotion_1.Internals.portalNode().getBoundingClientRect();
        if (compositionRect.width === 0 || compositionRect.height === 0) {
            return;
        }
        const scale = compositionRect.width / currentCompositionMetadata.width;
        const currentTranslate = propStatus
            ? String((_d = (_c = remotion_1.Internals.getEffectiveVisualModeValue({
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                propStatus: propStatus,
                dragOverrideValue: dragOverrides[selected_outline_types_1.translateFieldKey],
                defaultValue: fieldSchema.default,
                frame: sourceFrame,
                shouldResortToDefaultValueIfUndefined: true,
            })) !== null && _c !== void 0 ? _c : fieldSchema.default) !== null && _d !== void 0 ? _d : '0px 0px')
            : String((_e = fieldSchema.default) !== null && _e !== void 0 ? _e : '0px 0px');
        const [currentX, currentY] = (0, timeline_translate_utils_1.parseTranslate)(currentTranslate);
        const { x: newX, y: newY } = (0, alignment_controls_1.computeAlignedTranslate)({
            direction,
            elementRect,
            compositionRect,
            currentTranslateX: currentX,
            currentTranslateY: currentY,
            scale,
        });
        const newValue = (0, timeline_translate_utils_1.serializeTranslate)(newX, newY);
        const undoLabels = {
            left: 'Align left',
            'center-h': 'Align center horizontally',
            right: 'Align right',
            top: 'Align top',
            'center-v': 'Align center vertically',
            bottom: 'Align bottom',
        };
        const label = undoLabels[direction];
        if (!propStatus || propStatus.status === 'static') {
            (0, save_sequence_prop_1.saveSequenceProps)({
                changes: [
                    {
                        fileName: nodePath.absolutePath,
                        nodePath,
                        fieldKey: selected_outline_types_1.translateFieldKey,
                        value: newValue,
                        defaultValue: fieldSchema.default !== undefined
                            ? JSON.stringify(fieldSchema.default)
                            : null,
                        schema: track.sequence.controls.schema,
                    },
                ],
                setPropStatuses,
                clientId: previewServerState.clientId,
                undoLabel: label,
                redoLabel: label,
            });
        }
        else {
            (0, call_add_keyframe_1.callAddSequenceKeyframe)({
                fileName: nodePath.absolutePath,
                nodePath,
                fieldKey: selected_outline_types_1.translateFieldKey,
                sourceFrame,
                value: newValue,
                schema: track.sequence.controls.schema,
                setPropStatuses,
                clientId: previewServerState.clientId,
            });
        }
    }, [
        previewServerState,
        track,
        currentCompositionMetadata,
        timelinePosition,
        propStatuses,
        getDragOverrides,
        setPropStatuses,
    ]);
    if (previewServerState.type !== 'connected' ||
        !track.nodePathInfo ||
        !track.sequence.controls ||
        !currentCompositionMetadata) {
        return null;
    }
    const renderNodePath = track.nodePathInfo.sequenceSubscriptionKey;
    const renderNodePropStatuses = remotion_1.Internals.getPropStatusesCtx(propStatuses, renderNodePath);
    const renderSourceFrame = timelinePosition - track.keyframeDisplayOffset;
    const renderDragOverrides = (_a = getDragOverrides(renderNodePath)) !== null && _a !== void 0 ? _a : {};
    const renderActiveSchema = (0, selected_outline_drag_1.getSelectedOutlineActiveSchema)({
        schema: track.sequence.controls.schema,
        currentRuntimeValueDotNotation: track.sequence.controls.currentRuntimeValueDotNotation,
        dragOverrides: renderDragOverrides,
        propStatus: renderNodePropStatuses,
        frame: renderSourceFrame,
    });
    const renderFieldSchema = renderActiveSchema === null || renderActiveSchema === void 0 ? void 0 : renderActiveSchema[selected_outline_types_1.translateFieldKey];
    const renderPropStatus = renderNodePropStatuses === null || renderNodePropStatuses === void 0 ? void 0 : renderNodePropStatuses[selected_outline_types_1.translateFieldKey];
    if ((renderFieldSchema === null || renderFieldSchema === void 0 ? void 0 : renderFieldSchema.type) !== 'translate') {
        return null;
    }
    const alignmentDisabled = !isPropStatusDraggable(renderPropStatus);
    return (jsx_runtime_1.jsxs("div", { style: container, children: [
            jsx_runtime_1.jsx(AlignmentButton, { title: "Align left", onClick: () => handleAlign('left'), Icon: align_left_1.AlignLeftIcon, disabled: alignmentDisabled }), jsx_runtime_1.jsx(AlignmentButton, { title: "Align center horizontally", onClick: () => handleAlign('center-h'), Icon: align_center_horizontal_1.AlignCenterHorizontalIcon, disabled: alignmentDisabled }), jsx_runtime_1.jsx(AlignmentButton, { title: "Align right", onClick: () => handleAlign('right'), Icon: align_right_1.AlignRightIcon, disabled: alignmentDisabled }), jsx_runtime_1.jsx("div", { style: verticalDivider }), jsx_runtime_1.jsx(AlignmentButton, { title: "Align top", onClick: () => handleAlign('top'), Icon: align_top_1.AlignTopIcon, disabled: alignmentDisabled }), jsx_runtime_1.jsx(AlignmentButton, { title: "Align center vertically", onClick: () => handleAlign('center-v'), Icon: align_center_vertical_1.AlignCenterVerticalIcon, disabled: alignmentDisabled }), jsx_runtime_1.jsx(AlignmentButton, { title: "Align bottom", onClick: () => handleAlign('bottom'), Icon: align_bottom_1.AlignBottomIcon, disabled: alignmentDisabled })
        ] }));
};
exports.AlignmentControls = AlignmentControls;
