const audio = document.querySelector('audio');
const audioPlayer = document.getElementById('audio-player');
const audioTitle = document.getElementById('audio-title');
const durationContainer = document.getElementById('duration');
const seekSlider = document.getElementById('seek-slider');
const currentTimeContainer = document.getElementById('current-time');
const playIconContainer = document.getElementById('play-icon');
const volumeSlider = document.getElementById('volume-slider');

const showInfo = document.getElementById('show-info');

let shows = document.getElementById('showlist').children;

for (var i = 0; i < shows.length; i += 1)
{
    let show = shows[i];
    let urlSpan = show.children[1];
    let audioURL = urlSpan.textContent;
    show.addEventListener('click', () => {
        audioTitle.textContent = show.children[0].textContent;
        audioPlayer.classList.remove('hidden');
        audio.src = audioURL;
        audio.load();
        showInfo.removeChild(showInfo.children[0]);
        showInfo.appendChild(show.children[2].cloneNode(true));
        showInfo.children[0].classList.remove('hidden');
    });
}

const PlayState = {
    Play: 'Play',
    Pause: 'Pause'
}

let playState = PlayState.Pause;

const calculateTimeString = (secs) => {
    const hours = Math.floor(secs / (60 * 60));
    const minutes = String(Math.floor(secs / 60) - (60 * hours)).padStart(2, '0');
    const seconds = String(Math.floor(secs % 60)).padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
}

const displayDuration = () => {
    durationContainer.textContent = calculateTimeString(audio.duration);
}

const setSliderMax = () => {
    seekSlider.max = Math.floor(audio.duration);
}

seekSlider.addEventListener('input', () => {
    currentTimeContainer.textContent = calculateTimeString(seekSlider.value);
});

seekSlider.addEventListener('change', () => {
    audio.currentTime = seekSlider.value;
    currentTimeContainer.textContent = calculateTimeString(seekSlider.value);
});

audio.addEventListener('timeupdate', () => {
    seekSlider.value = Math.floor(audio.currentTime);
    currentTimeContainer.textContent = calculateTimeString(seekSlider.value);
});

playIconContainer.addEventListener('click', () => {
    if(playState === PlayState.Pause) {
        audio.play();
        playState = PlayState.Play;
        playIconContainer.textContent = '❚❚';
    } else {
        audio.pause();
        playState = PlayState.Pause;
        playIconContainer.textContent = '▶';
    }
});

volumeSlider.addEventListener('input', (e) => {
    const value = e.target.value;
    audio.volume = value / 100;
});

if (audio.readyState > 0) {
    displayDuration();
    setSliderMax();
} else {
    audio.addEventListener('loadedmetadata', () => {
        displayDuration();
        setSliderMax();
    });
}