import React, { useEffect, useRef } from 'react';
import Engine from '../../../engine';
import useEngine from '../../../hooks/useEngine';
import { RankingTrackProps } from '../../../model/rankingTrack';

const setupRanking = async (engine: Engine): Promise<void> => {
  await engine.setupScene();
  setTimeout(engine.setupRenderLoop, 0);
};

const DynamicRanking: React.FC<RankingTrackProps> = (props) => {
  const { teams } = props;
  const [engine, canvasRef] = useEngine(true);
  const teamsRefs = new Array(teams.length)
    .fill(1)
    .map(() => useRef<HTMLDivElement>());

  useEffect((): void => {
    if (engine) {
      engine.rankingProps = props;
      engine.teamsRefs = teamsRefs;
      setupRanking(engine);
    }
  }, [engine]);

  if (engine) {
    engine.teamsRefs = teamsRefs;
  }
  return (
    <article className="fullRankingCanvas">
      <canvas ref={canvasRef} />
      {teams.map((x, i) => (
        <div
          key={x.id}
          ref={teamsRefs[i]}
          title={x.name}
          className={`rankingCircle${x.position < 3 ? ' top' : ''}`}
        >
          {x.position + 1}
        </div>
      ))}
    </article>
  );
};
export default DynamicRanking;
