import type { ToolMode } from "../core/tool-mode";
import { DEFAULT_GRID_SIZE, snapPositiveSizeToGrid } from "../geometry/grid-snapping";
import {
  cloneBrushGeometry,
  scaleBrushGeometryToSize,
  updateBrush
} from "../document/brushes";

import { createOpaqueId } from "../core/ids";
import type { EditorSelection } from "../core/selection";
import type { Vec3 } from "../core/vector";

import { cloneSelectionForCommand, getBoxBrushOrThrow, replaceBrush, setSingleBrushSelection } from "./brush-command-helpers";
import type { EditorCommand } from "./command";

interface ResizeBoxBrushCommandOptions {
  brushId: string;
  size: Vec3;
  snapToGrid?: boolean;
  gridSize?: number;
  label?: string;
}

export function createResizeBoxBrushCommand(options: ResizeBoxBrushCommandOptions): EditorCommand {
  const resolvedSize =
    options.snapToGrid === false ? options.size : snapPositiveSizeToGrid(options.size, options.gridSize ?? DEFAULT_GRID_SIZE);

  let previousSize: Vec3 | null = null;
  let previousGeometry: ReturnType<typeof cloneBrushGeometry> | null = null;
  let previousSelection: EditorSelection | null = null;
  let previousToolMode: ToolMode | null = null;

  return {
    id: createOpaqueId("command"),
    label: options.label ?? "Resize box brush",
    execute(context) {
      const currentDocument = context.getDocument();
      const brush = getBoxBrushOrThrow(currentDocument, options.brushId);

      if (previousSize === null) {
        previousSize = {
          ...brush.size
        };
        previousGeometry = cloneBrushGeometry(brush.geometry);
      }

      if (previousSelection === null) {
        previousSelection = cloneSelectionForCommand(context.getSelection());
      }

      if (previousToolMode === null) {
        previousToolMode = context.getToolMode();
      }

      const nextGeometry = scaleBrushGeometryToSize(brush.geometry, resolvedSize);

      context.setDocument(
        replaceBrush(
          currentDocument,
          updateBrush(brush, {
            size: {
              ...resolvedSize
            },
            geometry: nextGeometry
          })
        )
      );
      context.setSelection(setSingleBrushSelection(options.brushId));
      context.setToolMode("select");
    },
    undo(context) {
      if (previousSize === null || previousGeometry === null) {
        return;
      }

      const currentDocument = context.getDocument();
      const brush = getBoxBrushOrThrow(currentDocument, options.brushId);

      context.setDocument(
        replaceBrush(
          currentDocument,
          updateBrush(brush, {
            size: {
              ...previousSize
            },
            geometry: cloneBrushGeometry(previousGeometry)
          })
        )
      );

      if (previousSelection !== null) {
        context.setSelection(previousSelection);
      }

      if (previousToolMode !== null) {
        context.setToolMode(previousToolMode);
      }
    }
  };
}
