"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.outlinesAreEqual = exports.measureOutlines = exports.getSequencesWithSelectableOutlines = exports.getSelectedTransformOriginInfo = exports.getSelectedEffectFieldsBySequenceKey = exports.getOutlineSelectionInteraction = exports.getSequenceKeysContainingSelection = exports.getSelectedSequenceKeys = exports.getTransformedSvgViewportPoints = exports.getSelectedOutlineRotationPivot = exports.getSelectedOutlineRotationCornerInfo = exports.getRotationCursor = exports.getSelectedOutlineRotationDeltaDegrees = exports.getAngleDegrees = exports.vectorBetween = exports.vectorLength = exports.dot = exports.getOutlineCenter = exports.midpoint = exports.pointToString = void 0;
const calculate_timeline_1 = require("../helpers/calculate-timeline");
const colors_1 = require("../helpers/colors");
const get_box_quads_ponyfill_1 = require("../helpers/get-box-quads-ponyfill");
const selected_outline_geometry_1 = require("./selected-outline-geometry");
const selected_outline_types_1 = require("./selected-outline-types");
const selected_outline_uv_1 = require("./selected-outline-uv");
const parse_keyframe_field_from_node_path_1 = require("./Timeline/parse-keyframe-field-from-node-path");
const TimelineSelection_1 = require("./Timeline/TimelineSelection");
const transform_origin_utils_1 = require("./Timeline/transform-origin-utils");
const pointToString = (point) => `${point.x},${point.y}`;
exports.pointToString = pointToString;
const midpoint = (from, to) => {
    return (0, selected_outline_geometry_1.mixPoint)(from, to, 0.5);
};
exports.midpoint = midpoint;
const getOutlineCenter = (points) => {
    const [tl, tr, br, bl] = points;
    return {
        x: (tl.x + tr.x + br.x + bl.x) / 4,
        y: (tl.y + tr.y + br.y + bl.y) / 4,
    };
};
exports.getOutlineCenter = getOutlineCenter;
const dot = (left, right) => {
    return left.x * right.x + left.y * right.y;
};
exports.dot = dot;
const vectorLength = (vector) => {
    return Math.hypot(vector.x, vector.y);
};
exports.vectorLength = vectorLength;
const vectorBetween = (from, to) => {
    return { x: to.x - from.x, y: to.y - from.y };
};
exports.vectorBetween = vectorBetween;
const getAngleDegrees = (from, to) => {
    return Math.atan2(to.y - from.y, to.x - from.x) * (180 / Math.PI);
};
exports.getAngleDegrees = getAngleDegrees;
const getSelectedOutlineRotationDeltaDegrees = ({ from, to, }) => {
    return ((((to - from) % 360) + 540) % 360) - 180;
};
exports.getSelectedOutlineRotationDeltaDegrees = getSelectedOutlineRotationDeltaDegrees;
const normalizeRotationCursorDegrees = (rotation) => {
    const normalizedRotation = ((rotation % 360) + 360) % 360;
    return Number(normalizedRotation.toFixed(3));
};
const getRotationCursor = (rotation) => {
    const normalizedRotation = normalizeRotationCursorDegrees(rotation);
    const transform = normalizedRotation === 0
        ? ''
        : `<g transform="rotate(${normalizedRotation} 32 32)">`;
    const transformEnd = normalizedRotation === 0 ? '' : '</g>';
    const svg = `<svg width="24" height="24" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">${transform}<g transform="scale(0.876712329)" filter="url(#filter0_d_1_14)"><path d="M10.9111 17.7687C10.3413 18.3701 10.367 19.3195 10.9684 19.8893L20.7687 29.1738C21.3701 29.7436 22.3195 29.7179 22.8893 29.1165C23.459 28.5151 23.4334 27.5657 22.832 26.996L14.1206 18.7431L22.3735 10.0316C22.9432 9.43022 22.9176 8.48082 22.3162 7.91107C21.7148 7.34133 20.7654 7.36699 20.1956 7.96839L10.9111 17.7687ZM49.3923 58.3118C49.9509 58.9235 50.8996 58.9667 51.5114 58.4081L61.481 49.3055C62.0927 48.7469 62.1359 47.7981 61.5773 47.1863C61.0187 46.5745 60.0699 46.5314 59.4581 47.09L50.5963 55.1812L42.5051 46.3194C41.9465 45.7076 40.9977 45.6645 40.386 46.2231C39.7742 46.7817 39.7311 47.7304 40.2896 48.3422L49.3923 58.3118ZM12.6747 18.7431L13 19.8893C22.1283 19.6426 30.7584 21.4283 37.8564 26.6927C44.8518 31.8809 49.734 39.8538 49 56H50.5963H51.5114C52.2774 39.1461 47.6482 30.2198 39.6436 24.2831C31.7416 18.4224 22.3717 17.2467 13 17.5L12.6747 18.7431Z" fill="${colors_1.BLACK}"/><path d="M19.1064 6.93652C20.2459 5.73379 22.1448 5.68278 23.3477 6.82227C24.5505 7.96181 24.6022 9.86076 23.4629 11.0635L18.7373 16.0508C26.3487 16.4239 33.9128 18.1651 40.5371 23.0781C44.7339 26.1907 48.0794 30.1189 50.2568 35.4834C51.9666 39.6958 52.9327 44.7395 53.0742 50.8867L58.4463 45.9824C59.6697 44.8654 61.5673 44.9514 62.6846 46.1748C63.8018 47.3985 63.7155 49.296 62.4922 50.4131L52.5225 59.5156C51.337 60.5979 49.5196 60.5507 48.3916 59.4346L48.2842 59.3232L39.1816 49.3535C38.0648 48.1301 38.1507 46.2324 39.374 45.1152C40.5975 43.9979 42.4961 44.0841 43.6133 45.3076L47.4756 49.5381C47.1908 44.7613 46.2876 40.9448 44.9482 37.8291C43.0666 33.4521 40.2851 30.3614 36.9629 27.8975C31.8259 24.0875 25.8071 22.1663 19.2891 21.5732L23.8633 25.9072C25.0662 27.0468 25.1178 28.9457 23.9785 30.1484C22.8746 31.3135 21.0576 31.3982 19.8516 30.3662L19.7373 30.2627L9.93652 20.9785C8.73384 19.839 8.6828 17.9401 9.82227 16.7373L19.1064 6.93652Z" stroke="${colors_1.WHITE}" stroke-width="3"/></g>${transformEnd}<defs><filter id="filter0_d_1_14" x="0" y="0" width="72.4696" height="72.3004" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dy="3"/><feGaussianBlur stdDeviation="3.75"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_1_14"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_1_14" result="shape"/></filter></defs></svg>`;
    return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 12 12, alias`;
};
exports.getRotationCursor = getRotationCursor;
const rotationCursorBaseDegrees = {
    'top-left': 270,
    'top-right': 0,
    'bottom-right': 90,
    'bottom-left': 180,
};
const getOutlineRotationDegrees = (points) => {
    const [tl, tr] = points;
    return (0, exports.getAngleDegrees)(tl, tr);
};
const getRotationCursorDegrees = (points, corner) => normalizeRotationCursorDegrees(getOutlineRotationDegrees(points) + rotationCursorBaseDegrees[corner]);
const getSelectedOutlineRotationCornerInfo = (points, corner) => {
    const [tl, tr, br, bl] = points;
    const point = {
        'top-left': tl,
        'top-right': tr,
        'bottom-right': br,
        'bottom-left': bl,
    }[corner];
    const center = (0, exports.getOutlineCenter)(points);
    const cursorDegrees = getRotationCursorDegrees(points, corner);
    return {
        center,
        cursor: (0, exports.getRotationCursor)(cursorDegrees),
        cursorDegrees,
        point,
    };
};
exports.getSelectedOutlineRotationCornerInfo = getSelectedOutlineRotationCornerInfo;
const getSelectedOutlineRotationPivot = ({ dimensions, points, transformOriginValue, }) => {
    if (dimensions === null) {
        return (0, exports.getOutlineCenter)(points);
    }
    const parsed = (0, transform_origin_utils_1.parseTransformOrigin)(transformOriginValue);
    if (parsed === null) {
        return (0, exports.getOutlineCenter)(points);
    }
    const uv = (0, transform_origin_utils_1.parsedTransformOriginToUv)({
        parsed,
        width: dimensions.width,
        height: dimensions.height,
    });
    if (uv === null) {
        return (0, exports.getOutlineCenter)(points);
    }
    return (0, selected_outline_uv_1.getUvHandlePosition)(points, uv);
};
exports.getSelectedOutlineRotationPivot = getSelectedOutlineRotationPivot;
const rectToPoints = (elementRect, containerRect) => {
    const left = elementRect.left - containerRect.left;
    const top = elementRect.top - containerRect.top;
    const right = elementRect.right - containerRect.left;
    const bottom = elementRect.bottom - containerRect.top;
    return [
        { x: left, y: top },
        { x: right, y: top },
        { x: right, y: bottom },
        { x: left, y: bottom },
    ];
};
const getTransformedSvgViewportPoints = ({ viewport, ctm, containerRect, }) => {
    const transformPoint = (x, y) => ({
        x: ctm.a * x + ctm.c * y + ctm.e - containerRect.left,
        y: ctm.b * x + ctm.d * y + ctm.f - containerRect.top,
    });
    const left = viewport.x;
    const top = viewport.y;
    const right = viewport.x + viewport.width;
    const bottom = viewport.y + viewport.height;
    return [
        transformPoint(left, top),
        transformPoint(right, top),
        transformPoint(right, bottom),
        transformPoint(left, bottom),
    ];
};
exports.getTransformedSvgViewportPoints = getTransformedSvgViewportPoints;
const quadToPoints = (quad, containerRect) => {
    // `getBoxQuads`/the ponyfill returns the quad in viewport coordinates.
    // The overlay <svg> is unscaled (the canvas `scale()`/pan live on a sibling
    // container, not the svg), so 1 user unit == 1 px and we only need to move
    // the quad into the svg's local space by subtracting its viewport origin.
    // We deliberately do not pass `relativeTo` to the ponyfill: when the target
    // is not an ancestor of the element, the polyfill cannot resolve the
    // coordinate space and leaves the quad in viewport coordinates.
    return [
        { x: quad.p1.x - containerRect.left, y: quad.p1.y - containerRect.top },
        { x: quad.p2.x - containerRect.left, y: quad.p2.y - containerRect.top },
        { x: quad.p3.x - containerRect.left, y: quad.p3.y - containerRect.top },
        { x: quad.p4.x - containerRect.left, y: quad.p4.y - containerRect.top },
    ];
};
const isSvgSvgElement = (element) => {
    var _a;
    const ownerSvgSvgElement = (_a = element.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.SVGSVGElement;
    return ((typeof SVGSVGElement !== 'undefined' &&
        element instanceof SVGSVGElement) ||
        (ownerSvgSvgElement !== undefined && element instanceof ownerSvgSvgElement));
};
const getSvgSvgElementViewport = (element) => {
    const viewBox = element.viewBox.baseVal;
    if (viewBox.width > 0 && viewBox.height > 0) {
        return {
            x: viewBox.x,
            y: viewBox.y,
            width: viewBox.width,
            height: viewBox.height,
        };
    }
    return {
        x: 0,
        y: 0,
        width: element.width.baseVal.value,
        height: element.height.baseVal.value,
    };
};
const getSvgSvgElementOutlinePoints = (element, containerRect) => {
    const ctm = element.getScreenCTM();
    const viewport = getSvgSvgElementViewport(element);
    if (ctm === null || (viewport.width === 0 && viewport.height === 0)) {
        return null;
    }
    return (0, exports.getTransformedSvgViewportPoints)({
        viewport,
        ctm,
        containerRect,
    });
};
const getElementOutlinePoints = (element, containerRect) => {
    const elementRect = element.getBoundingClientRect();
    if (elementRect.width === 0 && elementRect.height === 0) {
        return null;
    }
    if (isSvgSvgElement(element)) {
        return getSvgSvgElementOutlinePoints(element, containerRect);
    }
    const quads = (0, get_box_quads_ponyfill_1.getBoxQuadsPonyfill)(element, {
        box: 'border',
    });
    const quad = quads === null || quads === void 0 ? void 0 : quads[0];
    if (!quad) {
        return rectToPoints(elementRect, containerRect);
    }
    return quadToPoints(quad, containerRect);
};
const getSelectedSequenceKeys = (selectedItems) => {
    return new Set(selectedItems
        .filter((item) => item.type === 'sequence')
        .map((item) => (0, TimelineSelection_1.getTimelineSequenceSelectionKey)(item.nodePathInfo)));
};
exports.getSelectedSequenceKeys = getSelectedSequenceKeys;
const getSequenceKeysContainingSelection = (selectedItems) => {
    return new Set(selectedItems
        .filter((item) => item.type !== 'guide')
        .map((item) => (0, TimelineSelection_1.getTimelineSequenceSelectionKey)(item.nodePathInfo)));
};
exports.getSequenceKeysContainingSelection = getSequenceKeysContainingSelection;
const getOutlineSelectionInteraction = ({ shiftKey, metaKey, ctrlKey, }) => ({
    shiftKey,
    toggleKey: metaKey || ctrlKey,
});
exports.getOutlineSelectionInteraction = getOutlineSelectionInteraction;
const getKeyframeOrEasingField = (item) => {
    if (item.type !== 'keyframe' && item.type !== 'easing') {
        return null;
    }
    return (0, parse_keyframe_field_from_node_path_1.parseKeyframeFieldFromNodePath)(item.nodePathInfo.auxiliaryKeys);
};
const getSelectedEffectFieldsBySequenceKey = (selectedItems) => {
    var _a;
    const selectedEffects = new Map();
    for (const item of selectedItems) {
        if (item.type === 'guide') {
            continue;
        }
        const sequenceKey = (0, TimelineSelection_1.getTimelineSequenceSelectionKey)(item.nodePathInfo);
        const effectsForSequence = (_a = selectedEffects.get(sequenceKey)) !== null && _a !== void 0 ? _a : new Map();
        const addSelectedFields = ({ effectIndex, fieldKey, allFields, }) => {
            var _a;
            const selectedFields = (_a = effectsForSequence.get(effectIndex)) !== null && _a !== void 0 ? _a : {
                allFields: false,
                fieldKeys: new Set(),
            };
            if (allFields) {
                selectedFields.allFields = true;
            }
            else if (fieldKey !== null) {
                selectedFields.fieldKeys.add(fieldKey);
            }
            effectsForSequence.set(effectIndex, selectedFields);
            selectedEffects.set(sequenceKey, effectsForSequence);
        };
        if (item.type === 'sequence-effect') {
            addSelectedFields({
                effectIndex: item.i,
                fieldKey: null,
                allFields: true,
            });
            continue;
        }
        if (item.type === 'sequence-effect-prop') {
            addSelectedFields({
                effectIndex: item.i,
                fieldKey: item.key,
                allFields: false,
            });
            continue;
        }
        const keyframedField = getKeyframeOrEasingField(item);
        if ((keyframedField === null || keyframedField === void 0 ? void 0 : keyframedField.type) === 'effect') {
            addSelectedFields({
                effectIndex: keyframedField.effectIndex,
                fieldKey: keyframedField.fieldKey,
                allFields: false,
            });
        }
    }
    return selectedEffects;
};
exports.getSelectedEffectFieldsBySequenceKey = getSelectedEffectFieldsBySequenceKey;
const getSelectedTransformOriginInfo = (selectedItems) => {
    if (selectedItems.length !== 1) {
        return null;
    }
    const [selectedItem] = selectedItems;
    if (selectedItem.type === 'sequence-prop' &&
        selectedItem.key === selected_outline_types_1.transformOriginFieldKey) {
        return {
            sequenceKey: (0, TimelineSelection_1.getTimelineSequenceSelectionKey)(selectedItem.nodePathInfo),
            displayFrame: null,
        };
    }
    if (selectedItem.type !== 'keyframe' && selectedItem.type !== 'easing') {
        return null;
    }
    const field = getKeyframeOrEasingField(selectedItem);
    if ((field === null || field === void 0 ? void 0 : field.type) !== 'sequence' ||
        field.fieldKey !== selected_outline_types_1.transformOriginFieldKey) {
        return null;
    }
    return {
        sequenceKey: (0, TimelineSelection_1.getTimelineSequenceSelectionKey)(selectedItem.nodePathInfo),
        displayFrame: selectedItem.type === 'keyframe'
            ? selectedItem.frame
            : selectedItem.fromFrame,
    };
};
exports.getSelectedTransformOriginInfo = getSelectedTransformOriginInfo;
const getSequencesWithSelectableOutlines = ({ sequences, overrideIdsToNodePaths, compositions = [], }) => {
    return (0, calculate_timeline_1.calculateTimeline)({
        sequences: [...sequences],
        overrideIdsToNodePaths,
        compositions,
    })
        .filter((track) => {
        if (track.nodePathInfo === null) {
            return false;
        }
        return (track.sequence.showInTimeline &&
            track.nodePathInfo.auxiliaryKeys.length === 0);
    })
        .filter((track) => track.sequence.refForOutline !== null)
        .sort((a, b) => a.depth - b.depth)
        .map((track) => {
        if (track.nodePathInfo === null) {
            throw new Error('Expected selected outline to have a node path');
        }
        return {
            depth: track.depth,
            keyframeDisplayOffset: track.keyframeDisplayOffset,
            key: (0, TimelineSelection_1.getTimelineSequenceSelectionKey)(track.nodePathInfo),
            nodePathInfo: track.nodePathInfo,
            sequence: track.sequence,
        };
    });
};
exports.getSequencesWithSelectableOutlines = getSequencesWithSelectableOutlines;
const measureOutlines = (container, targets) => {
    const containerRect = container.getBoundingClientRect();
    const outlines = [];
    for (const target of targets) {
        const element = target.ref.current;
        if (element === null) {
            continue;
        }
        const points = getElementOutlinePoints(element, containerRect);
        if (points === null) {
            continue;
        }
        outlines.push({
            key: target.key,
            dimensions: element instanceof HTMLElement
                ? {
                    width: element.offsetWidth,
                    height: element.offsetHeight,
                }
                : element instanceof SVGSVGElement
                    ? {
                        width: element.width.baseVal.value,
                        height: element.height.baseVal.value,
                    }
                    : null,
            points,
        });
    }
    return outlines;
};
exports.measureOutlines = measureOutlines;
const outlinesAreEqual = (a, b) => {
    var _a, _b, _c, _d;
    if (a.length !== b.length) {
        return false;
    }
    for (let i = 0; i < a.length; i++) {
        if (a[i].key !== b[i].key) {
            return false;
        }
        if (((_a = a[i].dimensions) === null || _a === void 0 ? void 0 : _a.width) !== ((_b = b[i].dimensions) === null || _b === void 0 ? void 0 : _b.width) ||
            ((_c = a[i].dimensions) === null || _c === void 0 ? void 0 : _c.height) !== ((_d = b[i].dimensions) === null || _d === void 0 ? void 0 : _d.height)) {
            return false;
        }
        for (let j = 0; j < a[i].points.length; j++) {
            if (Math.abs(a[i].points[j].x - b[i].points[j].x) > 0.01 ||
                Math.abs(a[i].points[j].y - b[i].points[j].y) > 0.01) {
                return false;
            }
        }
    }
    return true;
};
exports.outlinesAreEqual = outlinesAreEqual;
