import Vector2 from "../../../../core/geom/Vector2.js";

/**
 *
 * @param {Keyframe} selectedKeyframe
 * @param {Vector2} deltaPosition
 * @param {AnimationCurve} curve
 */
export function updateKeyframePosition(selectedKeyframe, deltaPosition, curve) {
    selectedKeyframe.time += deltaPosition.x;
    selectedKeyframe.value += deltaPosition.y;
    updateKeyFrameIndexes(curve, selectedKeyframe);
}

/**
 *
 * @param {AnimationCurve} curve
 * @param {Keyframe} keyframe
 */
function updateKeyFrameIndexes(curve, keyframe) {
    let keyframeIndex = curve.keys.indexOf(keyframe);

    if (keyframeIndex < (curve.keys.length - 1) && keyframe.time > curve.keys[keyframeIndex + 1].time) {
        const nextIndex = keyframeIndex + 1;
        const next = curve.keys[nextIndex];

        curve.keys[nextIndex] = keyframe;
        curve.keys[keyframeIndex] = next;

    } else if (keyframeIndex > 0 && keyframe.time < curve.keys[keyframeIndex - 1].time) {
        const prevIndex = keyframeIndex - 1;
        const prev = curve.keys[prevIndex];

        curve.keys[prevIndex] = keyframe;
        curve.keys[keyframeIndex] = prev;

    }
}