"use strict";

const Promise = require("bluebird");
const awaitVideoElementLoad = require("../await-video-element-load");

function trySetSrcObject(element, file) {
	if ("srcObject" in element) {
		try {
			element.srcObject = file;
			return true;
		} catch (error) {
			if (error.name === "TypeError") {
				return false;
			} else {
				throw error;
			}
		}
	} else {
		return false;
	}
}

module.exports = function loadVideoFile(file) {
	// FIXME: Validation
	let cleanupFunction;
	let element = document.createElement("video");

	if (!trySetSrcObject(element, file)) {
		let objectURL = URL.createObjectURL(file);
		element.src = objectURL;
		// FIXME: Verify that this works correctly, and doesn't prematurely kill the video!
		cleanupFunction = () => URL.revokeObjectURL(objectURL);
	}

	return Promise.try(() => {
		return awaitVideoElementLoad(element);
	}).then(() => {
		if (cleanupFunction != null) {
			cleanupFunction();
		}

		return element;
	});
};
