/** @jsx jsx */
import { jsx } from '@emotion/core';
import styled from '@emotion/styled';
import { useCallback, useContext, useRef } from 'react';
import { PlayerContext } from '../../hooks/useProjectPlayer';
import { ScreenConfigurationContext } from '../../hooks/useScreenConfiguration';
import { openToolbarWidth, navHeight, closedToolbarWidth } from '../../styles/dimensions';
import { TimelineViewControllerContext } from '../../hooks/useTimelineViewController';
import useAnimationFrame from '../../hooks/useAnimationFrame';
import { samplesToViewportPx } from './calculator';

const PlayheadDisplay = styled.div`
position: fixed;
top: ${navHeight}px;
bottom: 0;
width: 1px;
background-color: white;
`;

export default () => {
  const screenConfiguration = useContext(ScreenConfigurationContext);
  const { fastGetCurrentTimeRef } = useContext(PlayerContext);
  const { getCombinedState } = useContext(TimelineViewControllerContext);
  const timelineLeft = screenConfiguration.toolbarOpen ? openToolbarWidth : closedToolbarWidth;
  const playheadRef = useRef<HTMLDivElement>(null);
  const lastPlayheadPosition = useRef<number | null>(null);

  const setPosition = useCallback(
    (playheadPosition: number) => {
      const ref = playheadRef.current
      if (!ref) return;
      if (lastPlayheadPosition.current === playheadPosition) {
        return;
      }
      lastPlayheadPosition.current = playheadPosition;
      ref.setAttribute('style', `left: ${playheadPosition < 0 ? -10000 : timelineLeft + playheadPosition}px`);
    },
    [timelineLeft]
  );

  const frameCallback = useCallback(
    () => {
      const currentTime = fastGetCurrentTimeRef.current();
      const playheadPosition = samplesToViewportPx(getCombinedState(), currentTime);
      setPosition(playheadPosition);
    },
    [fastGetCurrentTimeRef, getCombinedState, setPosition]
  );

  useAnimationFrame(frameCallback);

  return (
    <PlayheadDisplay ref={playheadRef} />
  );
}
