import './style.scss'
import { Canvas, useFrame } from '@react-three/fiber';
import Notes from './components/notes';
import Player from './components/player';
import Ground from './components/ground';
import React, { Suspense, useContext, useEffect, useState } from 'react';
import { Physics } from '@react-three/rapier';

export const AppContext = React.createContext(null);

function KeyPressedClearer() {
    const { setKeysPressed } = useContext(AppContext);
    useFrame((_s, _d) => setKeysPressed([]));
    return <></>
}

function App() {
    const [keys, setKeys] = useState([]);
    const [keysPressed, setKeysPressed] = useState([]);
    const playerKeyDown = (event) => {
        setKeys(keys => {
            if(!keys.includes(event.code)) {
                setKeysPressed(keysPressed => [...keysPressed, event.code]);
            }
         return [...keys, event.code]
        });
    }
    const playerKeyUp = (event) => {
        setKeys(keys => keys.filter(k => k != event.code));
    }
    useEffect(() => {
        window.addEventListener('keydown', playerKeyDown);
        window.addEventListener('keyup', playerKeyUp);
        return () => {
            window.removeEventListener('keydown', playerKeyDown);
            window.removeEventListener('keyup', playerKeyUp);
        };
    }, []);
    return (
        <AppContext.Provider value={{ keys: keys, keysPressed: keysPressed, setKeysPressed: setKeysPressed }}>
            <Canvas shadows>
                <KeyPressedClearer />
                <Suspense>
                    <Physics timeStep={1/60}>
                        <directionalLight
                            castShadow
                            position={[100, 100, 100]}
                            lookAt={[0, 0, 0]}
                            intensity={Math.PI / 2}
                            shadow-mapSize-height={2048}
                            shadow-mapSize-width={2048}
                        />
                        <ambientLight intensity={Math.PI / 4} />
                        <Notes />
                        <Player />
                        <Ground />
                    </Physics>
                </Suspense>
            </Canvas>
        </AppContext.Provider>
    )
}

export default App;
