import { statusStyle } from "../../tgu-planning/tguStatus";
import type { MapProjection } from "../geometry/mapProjection";
import type { MapPolygon } from "../model/mapTypes";

export function drawPlanWorks(
  ctx: CanvasRenderingContext2D,
  polygons: MapPolygon[],
  projection: MapProjection,
  viewport: { width: number; height: number }
) {
  ctx.save();
  for (const polygon of polygons) {
    if (polygon.points.length < 3) continue;
    const screenPoints = polygon.points.map((point) => projection.project(point));
    if (!screenPoints.some((point) => point.x >= -32 && point.x <= viewport.width + 32 && point.y >= -32 && point.y <= viewport.height + 32)) {
      continue;
    }

    const color = statusStyle(polygon.status || "PLANNED").color;
    ctx.beginPath();
    screenPoints.forEach((point, index) => {
      if (index === 0) {
        ctx.moveTo(point.x, point.y);
      } else {
        ctx.lineTo(point.x, point.y);
      }
    });
    ctx.closePath();
    ctx.fillStyle = hexToRgba(color, 0.2);
    ctx.strokeStyle = hexToRgba(color, 0.72);
    ctx.lineWidth = 1.2;
    ctx.fill();
    ctx.stroke();
  }
  ctx.restore();
}

function hexToRgba(hex: string, alpha: number): string {
  const value = hex.replace("#", "");
  const red = Number.parseInt(value.slice(0, 2), 16);
  const green = Number.parseInt(value.slice(2, 4), 16);
  const blue = Number.parseInt(value.slice(4, 6), 16);
  return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}

