import type { ToolType } from "../store/editorStore.types";
import { clampPositionToStage, fitSizeToStage } from "./stageBounds";

const IMAGE_MAX_SIZE = 400;

export const scaleImageDimensions = (
  naturalWidth: number,
  naturalHeight: number,
  maxSize = IMAGE_MAX_SIZE,
) => {
  let width = naturalWidth;
  let height = naturalHeight;

  if (width > maxSize || height > maxSize) {
    const ratio = Math.min(maxSize / width, maxSize / height);
    width = Math.round(width * ratio);
    height = Math.round(height * ratio);
  }

  return { width, height };
};

export const createImageObject = (
  imageUrl: string,
  centerX: number,
  centerY: number,
  width: number,
  height: number,
  stageWidth?: number,
  stageHeight?: number,
) => {
  let w = width;
  let h = height;
  if (stageWidth && stageHeight) {
    ({ width: w, height: h } = fitSizeToStage(w, h, stageWidth, stageHeight));
  }
  let x = Math.round(centerX - w / 2);
  let y = Math.round(centerY - h / 2);
  if (stageWidth && stageHeight) {
    ({ x, y } = clampPositionToStage(x, y, w, h, stageWidth, stageHeight));
  }
  return {
    id: `image-${Date.now()}`,
    type: "image" as ToolType,
    x,
    y,
    width: w,
    height: h,
    imageUrl,
  };
};
