import react, { useEffect, useRef } from 'react';
import { TileKey } from './Map';

interface TileProperties {
  x: number;
  y: number;
  tileSize: number;
  delay?: number;
  tileKey: TileKey;
}

const Tile: react.FC<TileProperties> = (props: TileProperties) => {
  //  console.log(`Rendering <Tile/>`);
  const g = useRef<SVGGElement>(null);

  const timeout = (ms: number) => {
    return new Promise((resolve) => setTimeout(resolve, ms));
  };

  useEffect(() => {
    const loadImage = async () => {
      const href = `https://tile.openstreetmap.org/${props.tileKey.zoomLevel}/${props.tileKey.x}/${props.tileKey.y}.png`;
      console.log(`Pre loading: ${JSON.stringify(href)}`);
      const image = new Image(props.tileSize, props.tileSize);
      image.loading = 'eager';
      // @ts-ignore
      image.setAttribute('href', href);
      if (!image.complete) {
        await image.decode();
      }
      if (props.delay !== undefined) {
        await timeout(props.delay);
      }
      const svgImage = document.createElementNS(
        'http://www.w3.org/2000/svg',
        'image'
      ) as unknown as SVGImageElement;
      svgImage.setAttribute('width', props.tileSize.toString());
      svgImage.setAttribute('height', props.tileSize.toString());
      // @ts-ignore
      svgImage.setAttribute('href', href);
      g.current?.replaceChildren(svgImage);
    };
    loadImage();
  }, [props.delay, props.tileSize]);

  return (
    <>
      <g ref={g} transform={`translate(${props.x},${props.y})`} />
    </>
  );
};

export default Tile;
