import react, { useEffect, useRef } from 'react';

interface TileProperties {
  href?: string;
  x: number;
  y: number;
  tileSize: number;
  delay?: number;
}

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(() => {
    if (props.href !== undefined) {
      const loadImage = async () => {
        console.log(`Pre loading: ${JSON.stringify(props.href)}`);
        const image = new Image(props.tileSize, props.tileSize);
        //      const image:SVGImageElement = document.createElement('image') as unknown as SVGImageElement;
        //      const image = new SVGImageElement();
        image.loading = 'eager';
        // @ts-ignore
        image.setAttribute('href', props.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', props.href);
        // svgImage.setAttribute('x', '0');
        // svgImage.setAttribute('y', '0');
        g.current?.replaceChildren(svgImage);
      };
      loadImage();
    }
 }, [props.href, props.delay, props.tileSize]);

  // const children = useMemo(
  //   () => (
  //     <>
  //       <g ref={g} transform={`translate(${props.x},${props.y})`} />
  //     </>
  //   ),
  //   []
  // );

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

export default Tile;
