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

const AudioResult = function(title, src) {
	Result.call(this, title);
	this.src = src;
}
AudioResult.prototype = Object.assign(Object.create(Result.prototype), {
	getHTML: function() {
		this.html.classList.add('audio-result');
		this.html.innerHTML = `<div class="title">🎵 ${this.title}</div>` + (this.subtitle ? `<div class="subtitle">${this.subtitle}</div>` : '');
	
		this.player = new Audio(this.src);
		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.seekbar = document.createElement('div');
		this.seekbar.classList.add('seekbar');
		this.seekbar.style.transform = 'translateX(-100%)';
		this.html.appendChild(this.seekbar);
	
		this.update();
		return this.html;
	},
	play: function() {
		if(this.player)
			this.player.play();
	},
	pause: function() {
		if(this.player)
			this.player.pause();
	},
	playPause: function() {
		if(this.player && this.player.paused)
			this.player.play();
		else if(this.player)
			this.player.pause();
	},
	seekForward: function() {
		if(this.player) {
			if(this.player.currentTime+5 < this.player.duration)
				this.player.currentTime += 5;
			else
				this.player.currentTime = this.player.duration;
		}
	},
	seekBackward: function() {
		if(this.player) {
			if(this.player.currentTime-5 > 0)
				this.player.currentTime -= 5;
			else
				this.player.currentTime = 0;
		}
	},
	update: function() {
		if(this.player) {
			var seekPercentage = this.player.currentTime*100/this.player.duration;
			this.seekbar.style.transform = `translateX(-${100 - seekPercentage}%)`;
		}
		requestAnimationFrame(_ => this.update());
	},
	destroy: function() {
		if(this.player)
			this.player.pause();
		Result.prototype.destroy.call(this);
	},
	onselect: function() {
		if(this.player && this.player.paused)
			this.player.play();
	},
	onunselect: function() {
		if(this.player && !this.player.paused)
			this.player.pause();
	},
	leftAction: function() {
		this.seekBackward();
	},
	rightAction: function() {
		this.seekForward();
	}
});

module.exports = AudioResult;