import {MouseEvent as ReactMouseEvent, ReactElement, useContext, useMemo} from "react";
import {HexCell} from "../../../common/src/state/HexMap";
import {
    renderCoordinatesToPolygonPoints, RenderOffsets,
    StorageCoordinates,
    storageCoordinatesToRenderCoordinates
} from "../../../common/src/state/Coordinates";
import {DispatchContext} from "./context/DispatchContext";
import {TILE_PAINT, TILE_REMOVE} from "../../../common/src/actions/TileAction";

export function HexTileRenderer({classNames, coords, cell, offsets}: {classNames?: readonly string[], coords: StorageCoordinates, cell: HexCell, offsets: RenderOffsets}): ReactElement {
    const dispatch = useContext(DispatchContext);

    const LMB = 1;
    const RMB = 2;

    function onMouse(e: ReactMouseEvent<SVGPolygonElement, MouseEvent>) {
        if (dispatch === null) {
            return;
        }
        if (e.buttons === LMB) {
            dispatch({
                type: TILE_PAINT,
                at: coords,
            });
        }
        if (e.buttons === RMB) {
            dispatch({
                type: TILE_REMOVE,
                at: coords,
            });
        }
    }

    const renderCoordinates = useMemo(() => storageCoordinatesToRenderCoordinates(coords, offsets), [coords, offsets]);
    const points = useMemo(() => renderCoordinatesToPolygonPoints(renderCoordinates), [renderCoordinates])

    return <polygon
        className={classNames !== undefined ? `hexagon mapTile ${classNames.join(" ")}` : "hexagon mapTile"}
        fill={cell.color}
        points={points}
        onMouseDown={onMouse}
        onMouseMove={onMouse}
        onContextMenu={(e) => e.preventDefault()}/>
}