'use strict';

const player = document.querySelector('.body-wrapper > .player');
const audio = player.querySelector('.core');

const handlerPlay = function(ev, id) {
    player.classList.add('active');

    changeSVGImage(player.querySelector('.button.play-pause'), 'icon-pause');

    player.querySelector('.time-slider').value = 0;
    player.querySelector('.time-slider').max = 0;
    player.querySelector('.time').innerHTML = '00:00';
    player.querySelector('.duration').innerHTML = '00:00';

    audio.src = '/api/recording/' + id + '?asFile=false';
    audio.volume = storageGet('player-volume') || 0.25;
    player.querySelector('.volume-slider').value = audio.volume;

    audio.load();
    audio.play();

    ev.stopPropagation();
};


(() => {
    let isDragging = false;

    const onLoadedMetadata = () => {
        if (audio.duration && !isNaN(audio.duration)) {
            player.querySelector('.duration').innerHTML = common.convertToDuration(Math.ceil(audio.duration));
            player.querySelector('.time-slider').max = audio.duration;

            audio.playbackRate = storageGet('player-speed') || 1;
            player.querySelector('.speed-slider').value = audio.playbackRate;
            player.querySelector('.current-speed').innerHTML = audio.playbackRate * 100 + "%";
        }
    };

    const onEnded = () => {
        changeSVGImage(player.querySelector('.button.play-pause'), 'icon-play-fill');

        player.querySelector('.time-slider').value = audio.duration;
        player.querySelector('.time').innerHTML = common.convertToDuration(Math.ceil(audio.duration));
    };


    const onError = e => {
        let errorText = "";
        switch (e.target.error.code) {
            case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
                errorText = "Файл записи не найден на сервере";
                break;
            case e.target.error.MEDIA_ERR_NETWORK:
                errorText = "Что-то произошло с сетевым подключением";
                break;
            case e.target.error.MEDIA_ERR_DECODE:
                errorText = "Проблема с декодированием аудиофайла";
                break;
            default:
                errorText = "Неизвестная ошибка: " + e.target.error.code;
        }

        showMessage({
            icon: 'icon-error',
            header: 'Ошибка!',
            text: errorText
        });

        player.classList.remove('active');
    };

    const handlerPlayPause = (ev, el) => {
        if (!audio.paused) {
            changeSVGImage(el, 'icon-play-fill');
            audio.pause();
        } else {
            changeSVGImage(el, 'icon-pause');
            audio.play();
        }
    };

    const handlerVolume = () => {
        player.querySelector('.volume-bar').classList.toggle('active');
    };

    const handlerSpeed = () => {
        player.querySelector('.speed-bar').classList.toggle('active');
    };

    const handlerClose = () => {
        player.classList.remove('active');
        audio.pause();
    };


    const handlerChangeVolume = (ev, el) => {
        if (el.value >= 0 && el.value <= 1) {
            audio.volume = el.value;
        }
    };
    const handlerSaveVolume = (ev, el) => {
        if (el.value >= 0 && el.value <= 1) {
            storageSet('player-volume', el.value);
        }
    };


    const handlerChangeSpeed = (ev, el) => {
        audio.playbackRate = el.value;
        player.querySelector('.current-speed').innerHTML = audio.playbackRate * 100 + "%";
    };
    const handlerSaveSpeed = (ev, el) => {
        if (el.value >= 0) {
            storageSet('player-speed', el.value);
        }
    };
    const handlerResetSpeed = (ev, el) => {
        el.value = 1;
        audio.playbackRate = 1;
        player.querySelector('.speed-slider').value = 1;
        player.querySelector('.current-speed').innerHTML = "100%";
        storageSet('player-speed', 1);
    };




    const handlerProgress = () => {
        if (!isNaN(audio.currentTime) && !isNaN(audio.duration)) {
            if (!isDragging) {
                player.querySelector('.time-slider').value = audio.currentTime;
            }
            player.querySelector('.time').innerHTML = common.convertToDuration(audio.currentTime);
        }
    };

    const handlerChangeTime = e => {
        if (!isNaN(audio.duration)) {
            const pb = player.querySelector('.time-slider');
            audio.currentTime = pb.value;
        }
    };



    createListener(player.querySelector('.button.play-pause'), 'click', handlerPlayPause);

    createListener(player.querySelector('.volume-slider'), 'input', handlerChangeVolume);
    createListener(player.querySelector('.volume-slider'), 'change', handlerSaveVolume);
    createListener(player.querySelector('.speed-slider'), 'input', handlerChangeSpeed);
    createListener(player.querySelector('.speed-slider'), 'change', handlerSaveSpeed);
    createListener(player.querySelector('.button.reset-speed'), 'click', handlerResetSpeed);


    player.querySelector('.button.volume').addEventListener('click', handlerVolume);
    player.querySelector('.button.speed').addEventListener('click', handlerSpeed);
    player.querySelector('.button.close').addEventListener('click', handlerClose);

    player.querySelector('.time-slider').addEventListener('change', handlerChangeTime);
    player.querySelector('.time-slider').addEventListener('mousedown', () => {isDragging = true});
    player.querySelector('.time-slider').addEventListener('mouseup', () => {isDragging = false});


    audio.addEventListener('timeupdate', handlerProgress);
    audio.addEventListener('loadedmetadata', onLoadedMetadata);
    audio.addEventListener('ended', onEnded);
    audio.addEventListener('error', onError);
})();
