import React, { useEffect, useRef } from 'react';
import { usePanoStartPosition, usePanoStartPov, useTargetPoint } from '../../../domain/gameStore';
import { savePanoPositionToLocalStorage, savePanoPovToLocalStorage } from '../../../domain/localStorageMethods';
import styles from './GamePanel.module.css';
import usePano from './usePano';

export default () => {
  const startPosition = usePanoStartPosition();
  const startPov = usePanoStartPov();
  const resetPosition = useTargetPoint();
  const panoDivRef = useRef(null);
  const panoRef = usePano(panoDivRef, startPosition, startPov);
  useEffect(
    () => {
      if (panoRef.current) {
        panoRef.current.addListener('position_changed', () => {
          const { lat, lng } = panoRef.current.getPosition();
          savePanoPositionToLocalStorage(lat(), lng());
        });
        panoRef.current.addListener('pov_changed', () => {
          const { heading, pitch } = panoRef.current.getPov();
          savePanoPovToLocalStorage(heading, pitch);
        });
      }
    },
    [ panoRef ]
  );

  return (
    <>
      <div className={styles.fullsize} ref={panoDivRef} />
      <div className={styles.resetButton} onClick={() => panoRef.current.setPosition(resetPosition)}>
        Reset
      </div>
    </>
  );
};
