import type Konva from "konva";

export const getObjectBorderRadius = (borderRadius?: number): number =>
  Math.max(0, borderRadius ?? 0);

export const clampBorderRadius = (
  radius: number,
  width: number,
  height: number,
): number => Math.max(0, Math.min(radius, width / 2, height / 2));

export const createRoundedRectClipFunc = (
  width: number,
  height: number,
  radius: number,
): Konva.ContainerConfig["clipFunc"] => {
  const r = clampBorderRadius(radius, width, height);
  if (r <= 0) return undefined;

  return (ctx) => {
    ctx.beginPath();
    ctx.roundRect(0, 0, width, height, r);
    ctx.closePath();
  };
};

export const getCssBorderRadius = (
  borderRadius: number | undefined,
  scale: number,
): string | undefined => {
  const r = getObjectBorderRadius(borderRadius) * scale;
  return r > 0 ? `${r}px` : undefined;
};
