// See https://davidwalsh.name/browser-camera

const shutterSound = new Audio('shutter.mp3');
const countdownSound = new Audio('ding.mp3');
let countingDown = false;

$(document).ready(function() {
	// Check if configuration is present
	try {
		BASEURL
	} catch (e) {
		alert("config.js not found!");
		return;
	}

	// Shutter button press
	$(window).keydown(function(event){
		switch(event.keyCode) {
			case 13:
			case 32:
				onShutterButtonPressed();
				break
			default:
				console.log(`Ignored keypress ${event.keyCode}`)
		}
	});

	// Get access to the camera!
	var video = $('#video')[0];
	if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
		// Not adding `{ audio: true }` since we only want video now
		navigator.mediaDevices.getUserMedia({ video: {
			width: 3840,
			height: 2160
		} }).then(function(stream) {
			//video.src = window.URL.createObjectURL(stream);
			video.srcObject = stream;
			video.play();
		});
	}
});

function onShutterButtonPressed() {
	if (!countingDown)
		countdown(COUNTDOWN_FROM, takePhoto);
}

function countdown(from, onCountdownElapsed) {
	countingDown = true;
	const countdownEl = $('#countdown');

	if (from > 0) {
		if (from === COUNTDOWN_FROM)
			countdownEl.show();
		countdownSound.play();
		setTimeout(function() {countdown(from - 1, onCountdownElapsed)}, 1000);
	} else {
		countingDown = false;
		countdownEl.hide();
		onCountdownElapsed();
	}
	countdownEl.text(from);
}

function takePhoto() {
	const canvas = $('#canvas');
	const canvasContainer = $('#canvas-container');
	const flash = $('#flash');
	const context = canvas[0].getContext('2d');
	context.drawImage(video, 0, 0, 3840, 2160);
	canvasContainer.show();
	flash.show();
	$('#video').addClass('blurred');
	shutterSound.play();
	uploadImage();

	// Hide flash
	setTimeout(function() {
		flash.hide();
	}, 200)

	// Hide canvas
	setTimeout(function() {
		canvasContainer.hide();
		$('#video').removeClass('blurred');
	}, 5000);
}

function uploadImage() {
	document.querySelector("#canvas").toBlob(function(blob) {
		let file = new File([blob], 'photobooth.jpg', { type: 'image/jpeg' });
		let data = new FormData();
		data.append('image', file);

		let request = new XMLHttpRequest();
		request.open('POST', `${BASEURL}/api/gallery_item/upload.php`);
		request.setRequestHeader('Authentication', TOKEN);
		request.addEventListener('load', function(e) {
			console.log(request.response);
		});
		request.send(data);
		saveLocalImage(file);
	}, 'image/jpeg', 1);
}

/**
 * Saves the image locally for backup
 */
function saveLocalImage(blob) {
	const fileName = `photobooth-${Date.now()}`
	if (typeof navigator.msSaveBlob == "function")
        return navigator.msSaveBlob(blob, fileName);

    var saver = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    var blobURL = saver.href = URL.createObjectURL(blob),
        body = document.body;

    saver.download = fileName;

    body.appendChild(saver);
    saver.dispatchEvent(new MouseEvent("click"));
    body.removeChild(saver);
    URL.revokeObjectURL(blobURL);
}
