const Result = require('./Result.js');

const VideoResult = function(title, source) {
	Result.call(this, title);
	this.source = source;
};
VideoResult.prototype = Object.create(Result.prototype);
VideoResult.prototype.getHTML = function() {
	this.html.classList.add('video-result');
	const title = document.createElement('header');
	title.innerHTML = `<div class="title">${this.title}</div>` + (this.subtitle ? `<div class="subtitle">${this.subtitle}</div>` : '');
	this.html.appendChild(title);
	this.player = document.createElement('video');
	this.player.src = this.source;
	this.player.preload = 'none';
	
	this.player.addEventListener('ended', _ => document.dispatchEvent(new Event('nextResult')));
	
	this.html.addEventListener('mousedown', _ => {
		this.clickStartX = _.clientX;
	});
	this.html.addEventListener('mousemove', _ => {
		if(_.buttons > 0 && this.player && Math.abs(this.clickStartX-_.clientX) > 10) {
			this.seeking = true;
			this.player.currentTime = this.player.duration * ((_.clientX-10)/this.html.clientWidth);
		}
	});
	this.html.addEventListener('mouseup', _ => {
		if(!this.seeking)
			this.playPause();
		else
			this.seeking = false;
	});

	this.html.appendChild(this.player);
	this.seekbar = document.createElement('div');
	this.seekbar.className = 'seekbar';
	this.html.appendChild(this.seekbar);
	this.update();
	return this.html;
};
VideoResult.prototype.playPause = function() {
	if(this.player && this.player.paused)
		this.player.play();
	else if(this.player)
		this.player.pause();
};
VideoResult.prototype.destroy = function() {
	if(this.player)
		this.player.pause();
	Result.prototype.destroy.call(this);
}
VideoResult.prototype.update = function() {
	if(this.player) {
		var seekPercentage = this.player.currentTime*100/this.player.duration;
		this.seekbar.style.transform = `translateX(-${100 - seekPercentage}%)`;
	}
	requestAnimationFrame(_ => this.update());
}
VideoResult.prototype.onselect = function() {
	if(this.player && this.player.paused)
		this.player.play();
}
VideoResult.prototype.onunselect = function() {
	if(this.player && !this.player.paused)
		this.player.pause();
}
VideoResult.prototype.leftAction = function() {
	if(this.player) {
		if(this.player.currentTime-5 > 0)
			this.player.currentTime -= 5;
		else
			this.player.currentTime = 0;
	}
}
VideoResult.prototype.rightAction = function() {
	if(this.player) {
		if(this.player.currentTime+5 < this.player.duration)
			this.player.currentTime += 5;
		else
			this.player.currentTime = this.player.duration;
	}
}

module.exports = VideoResult;