function readableMicroseconds(us) {
    const min = parseInt(us / 60_000_000);
    const sec = parseInt((us % 60_000_000) / 1_000_000);

    if (!min) {
        return `${sec}s`;
    }

    return `${min}m ${sec}s`;
}

async function main() {
    const response = await fetch(`/api/video-queue`);
    if (!response.ok) {
        error("something went wrong");
        return;
    }

    const json = await response.json();
    if (!json.ok) {
        error(json.error);
    }

    const queue = json.queue;

    document.getElementById("result").innerHTML =
        `<p>Currently processing ${queue.length} video(s)</p>`
        + `<ul id="video-list">`
        + queue
            .map(vid => {
                const percentage = parseInt(vid.progress / vid.duration * 100);
                const uploadedTime = readableMicroseconds(vid.progress);
                const totalTime = readableMicroseconds(vid.duration);

                return `
                    <li>
                        <div class="video-item">
                            <div class="video-image">
                                <img class="shadow" src="/videos/${vid.videoId}.png" alt="">
                                <img class="non-shadow" src="/videos/${vid.videoId}.png" alt="">
                            </div>
                            <span class="video-info">
                                <b>${vid.title}</b>
                                <br>
                                <p>Uploaded ${uploadedTime} of ${totalTime} (${percentage}%)</p>
                                <progress max="${vid.duration}" value="${vid.progress}">${percentage}%</progress>
                            </span>
                        </div>
                    </li>
                `;
            })
            .join("")
        + "</ul>";
}

main();

