import { useEffect } from "react";
import type { SightingType } from "../types/types";
import { drawRects } from "../utils/utils";

type Mode = 0 | 1 | 2;

export function useOverviewOverlay(
  selected: SightingType | null | undefined,
  overlayMode: Mode,
  imgRef: React.RefObject<HTMLImageElement | null>,
  canvasRef: React.RefObject<HTMLCanvasElement | null>
) {
  useEffect(() => {
    const img = imgRef?.current;
    const cvs = canvasRef?.current;
    if (!img || !cvs) return;

    const ctx = cvs.getContext("2d");
    if (!ctx) return;

    // clear
    ctx.clearRect(0, 0, cvs.width, cvs.height);

    if (!selected || overlayMode === 0) return;

    if (overlayMode === 1 && selected.overviewPlateRect) {
      drawRects(cvs, img, [selected.overviewPlateRect], "chartreuse");
    } else if (overlayMode === 2) {
      const rects = selected.plateTrack ?? [];
      if (rects.length) drawRects(cvs, img, rects, "yellow");
      if (selected.overviewPlateRect) {
        drawRects(cvs, img, [selected.overviewPlateRect], "chartreuse");
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selected?.ref, overlayMode, imgRef?.current?.src]);
}
