import Bar from './bar-class.js';
import Microphone from './microphone-class.js';
import { athenaConfigOptions } from '../../../../global/athena-config.js';

export default function waveAnimation()
{
    const DIVIDE_NUMBER = 256;
    const canvas = document.querySelector('#audio-search__canvas');
    const context = canvas.getContext('2d');
    const bars = [];
    const barWidth = canvas.width / DIVIDE_NUMBER;

    const microphone = new Microphone();

    athenaConfigOptions.microphoneClass = microphone;

    function createBars()
    {
        for(let i = 0; i < 256; i++) {
            bars.push(
                new Bar(
                    i * barWidth,
                    canvas.height / 2,
                    1,
                    100,
                    '#000000'
                )
            );
        }
    }

    createBars();

    function animate()
    {
        if(microphone.initialized) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            const samples = microphone.getSamples();

            bars.forEach((bar, index) => {
                bar.update(samples[index]);
                bar.draw(context);
            });
        }

        athenaConfigOptions.requestAnimationFrameId = requestAnimationFrame(animate);
    }

    animate();
}