export default modules => {
	let self

	self = {
		currentVolume: 0.5,

		setVolume: amount => {
			modules.globals.video.volume = Math.min(Math.max(amount, 0), 1)
			self.currentVolume = modules.globals.video.volume
		}
	}

	modules.globals.video.volume = self.currentVolume
	modules.controls.updateVolume(self.currentVolume)

	try {
		self.context = new(window.AudioContext || window.webkitAudioContext)
		self.result = {
			context: self.context,
			source: self.context.createMediaElementSource(modules.globals.video),
			gain: self.context.createGain(),
			media: modules.globals.video,
			amplify: m => self.result.gain.gain.value = m
		}
		self.result.source.connect(self.result.gain)
		self.result.gain.connect(self.context.destination)
		self.result.amplify(1)

		self.setVolume = amount => {
			amount = Math.max(amount, 0)
			amount = Math.min(amount, modules.controls.volumeBar.getAttribute("max"))
			self.currentVolume = amount
			modules.globals.video.volume = Math.min(amount, 1)

			if (amount > 1) {
				self.result.amplify(amount)
				modules.controls.volumeBar.value = self.currentVolume
				modules.controls.volumeText.innerHTML = `${Math.round(self.currentVolume * 100)}%`
			} else
				self.result.amplify(1)
		}

		// Raise max volume
		modules.controls.volumeBar.setAttribute("max", 3)

		// Stylize bar
		modules.controls.volumePopout.classList.add("boost")
		modules.controls.volumeBar.classList.add("boost")

		document.addEventListener("click", () => self.context.resume())

		// Force mono audio
		self.setNumChannels = num => self.context.destination.channelCount = num
		self.getNumChannels = () => self.context.destination.channelCount
	} catch (e) {
		console.error(`Volume boosting not allowed.\n${e}`)
	}

	return self
}
