"use strict";

const type    = "image/jpeg";
const quality = 0.95;
const width   = 1920;
const height  = 1440;

const camera  = document.getElementById("camera");
const message = document.createElement("div");
const video   = document.createElement("video");
const canvas  = document.createElement("canvas")
const ctx     = canvas.getContext("2d");

let facingMode = "environment";

async function getVideo() {
    try {
        video.srcObject = await navigator.mediaDevices.getUserMedia({
            video: { facingMode, width, height },
        });
        video.play();
    } catch (err) {
        camera.removeChild(video);
        message.innerHTML = `Could not get video: ${err.name}: ${err.message}`;
    }
}

async function post()
{
    try {
        message.innerHTML = "Posting...";
        canvas.width  = video.videoWidth;
        canvas.height = video.videoHeight;
        ctx.drawImage(video, 0, 0);
        const blob = await new Promise((r) => canvas.toBlob(r, type, quality));
        const resp = await fetch("/", {
            method: "POST",
            body:   blob,
        });
        message.innerHTML = `${resp.status}: ${resp.statusText}`;
    } catch (err) {
        message.innerHTML = `${err.name}: ${err.message}`;
    }
}

message.innerHTML = "Press video to post.";
video.addEventListener("click", post);
camera.appendChild(message);
camera.appendChild(video);
getVideo();
