async function formClick(ev) {
    ev.preventDefault();

    let { target } = ev;

    let fData = new FormData(target);

    let file = target.querySelector('input[type=file]');
    if (file)
        file.value = null;

    let fetched = await fetch(target.action, {
        'method': 'POST',
        'body': fData
    });

    let json = await fetched.json();

    target.querySelector('.form-message').textContent = json.message;

    if (json.redirect) {
        setTimeout(function () {
            window.location.href = json.redirect;
        }, 2000);
    }
}

function moveBar(e, bar, vid) {
    let rect = bar.getBoundingClientRect();
    let prog = ((e.pageX - rect.x) / rect.width);

    vid.currentTime = prog * vid.duration;
}

function prog(vid, bar) {
    bar.querySelector('div').style.width = `${vid.currentTime / vid.duration * 100}%`;
}

function controls(vid) {
    let isFull = false;
    let bar = vid.querySelector('.progressbar');
    let video = vid.querySelector('video');
    let play = vid.querySelector('.play');
    let h = document.querySelector('.header');

    video.onclick = play.onclick = () => {
        play.querySelector('img').src = !video.paused ? '/static/img/play.svg' : '/static/img/stop.svg';

        if (video.paused) {
            video.play();
            return;
        }
        video.pause();
    }

    vid.querySelector('.full').onclick = (e) => {
        isFull = !isFull;
        e.target.src = isFull ? '/static/img/tiny.svg' : '/static/img/full.svg';
        if (isFull) {
            vid.classList.add('full');
            h.classList.add('full');
        } else {
            vid.classList.remove('full');
            h.classList.remove('full');
        }
    }

    bar.onclick = (e) => moveBar(e, bar, video);

    video.addEventListener('timeupdate', () => prog(video,bar));
}

window.onload = function () {
    document.addEventListener('submit', formClick);
    for (let vid of document.querySelectorAll('.video-wrapper')) {
        controls(vid);
    }
}