import { CanvasRegion } from './CanvasRenderer';
import { Rectangle } from './canvasRendererTypes';

export default function crop(regions: CanvasRegion[], cropRect: Rectangle) {
  const adjustedRegions = regions.map((region) => {
    if (region.touchTarget) {
      return {
        ...region,
        touchTarget: {
          ...region.touchTarget,
          bounds: {
            top: Math.max(region.touchTarget.bounds.top, cropRect.top),
            left: Math.max(region.touchTarget.bounds.left, cropRect.left),
            bottom: Math.min(region.touchTarget.bounds.bottom, cropRect.bottom),
            right: Math.min(region.touchTarget.bounds.right, cropRect.right),
          },
        },
      };
    }
    return region;
  });

  return [
    {
      render: (ctx: CanvasRenderingContext2D) => {
        ctx.save();
        ctx.beginPath();
        ctx.rect(
          cropRect.left,
          cropRect.top,
          cropRect.right - cropRect.left,
          cropRect.bottom - cropRect.top
        );
        ctx.clip();
      },
    },
    ...adjustedRegions,
    {
      render: (ctx: CanvasRenderingContext2D) => {
        ctx.restore();
      },
    },
  ];
}
