import * as geo from "../lib/geometry.js";
import { defineGroup, YardGridLine } from "../lib/yard-features.js";
import { lotCorner } from "./anchors.js";

const GRID_SPACING_FEET = 10;
const MIN_EAST_FEET = -20;
const MAX_EAST_FEET = 180;
const MIN_NORTH_FEET = -140;
const MAX_NORTH_FEET = 20;

export const yardGridGroup = defineGroup("group:yard-grid", "Yard Grid");

function localPoint(eastFeet, northFeet) {
  return geo.offset(
    lotCorner,
    geo.east(geo.ft(eastFeet)),
    northFeet >= 0 ? geo.north(geo.ft(northFeet)) : geo.south(geo.ft(Math.abs(northFeet))),
  );
}

function makeNorthLine(eastFeet) {
  return new YardGridLine(`Grid east ${eastFeet} ft`, {
    axis: "north",
    offsetFeet: eastFeet,
    spacingFeet: GRID_SPACING_FEET,
  })
    .inGroup(yardGridGroup)
    .add(localPoint(eastFeet, MIN_NORTH_FEET))
    .add(localPoint(eastFeet, MAX_NORTH_FEET));
}

function makeEastLine(northFeet) {
  return new YardGridLine(`Grid north ${northFeet} ft`, {
    axis: "east",
    offsetFeet: northFeet,
    spacingFeet: GRID_SPACING_FEET,
  })
    .inGroup(yardGridGroup)
    .add(localPoint(MIN_EAST_FEET, northFeet))
    .add(localPoint(MAX_EAST_FEET, northFeet));
}

function rangeByFeet(minFeet, maxFeet, spacingFeet) {
  const values = [];

  for (let value = minFeet; value <= maxFeet; value += spacingFeet) {
    values.push(value);
  }

  return values;
}

const northLines = rangeByFeet(MIN_EAST_FEET, MAX_EAST_FEET, GRID_SPACING_FEET).map(makeNorthLine);
const eastLines = rangeByFeet(MIN_NORTH_FEET, MAX_NORTH_FEET, GRID_SPACING_FEET).map(makeEastLine);

export const gridFeatures = [...northLines, ...eastLines];
export const gridGroups = [yardGridGroup];
