class Music extends Window {
	constructor() {
		super('music')
		this.albumCoverElem = document.getElementById("album-art")
		this.currentlyPlayingElem = document.getElementById("currently-playing")
		this.currentSong = null

		this.songOrder = [
			'Down Polypore Wood',
			'Sneaking Out Alone',
			'Ritual Dance of The Cavern Walls Cult',
			'Tatari',
			'Buranko',
			'New Jersey Again',
			'Asteroids'
		]

		this.songMap = {
			'Down Polypore Wood': {
				'audio': 'Down Polypore Wood.mp3',
				'thumb': 'shrinkinminkin.jpg'
			},
			'Sneaking Out Alone': {
				'audio': 'Sneaking Out Alone.mp3',
				'thumb': 'shrinkinminkin.jpg'
			},
			'Ritual Dance of The Cavern Walls Cult': {
				'audio': 'Ritual Dance of The Cavern Walls Cult.mp3',
				'thumb': 'shrinkinminkin.jpg'
			},
			'Tatari': {
				'audio': 'Tatari.mp3',
				'thumb': 'tatari.jpg'
			},
			'Buranko': {
				'audio': 'buranko.mp3',
				'thumb': 'tatari.jpg'
			},
			'New Jersey Again': {
				'audio': 'new jersey again.mp3',
				'thumb': 'nj.jpg'
			},
			'Asteroids': {
				'audio': 'Asteroids.mp3',
				'thumb': 'amphi.jpg'
			},
		}
	}

	handleDialog() {
		indicator.hide('guitar')
	}

	resume() {
		if (!this.currentSong) {
			this.play(this.songOrder[0])
		}
		audio.play()
	}

	play(songName=null) {
		if (this.currentSong) {
			audio.pause()
		}
		
		if (!songName && !this.currentSong) {
			songName = this.songOrder[0]
		}

		this.currentSong = songName
		audio = new Audio(this.getSongFilepath(songName))
		audio.play()

		var self = this
		audio.addEventListener('ended', function() {
			self.next(self.currentSong)
		})

		this.albumCoverElem.src = this.getAlbumArtFilepath(songName)
		this.currentlyPlayingElem.innerHTML = this.currentSong
	}

	getSongFilepath(songName) {
		return `./assets/audio/${this.songMap[songName]['audio']}`
	}

	getAlbumArtFilepath(songName) {
		return `./assets/img/thumbnails/${this.songMap[songName]['thumb']}`
	}

	next() {
		if (this.currentSong) {
			var currentSongIndex = this.songOrder.indexOf(this.currentSong)
			var nextSongIndex = currentSongIndex + 1

			if (nextSongIndex > this.songOrder.length - 1) {
				nextSongIndex = 0
			}

			this.play(this.songOrder[nextSongIndex])
		}
	}

	prev() {
		if (this.currentSong) {
			var currentSongIndex = this.songOrder.indexOf(this.currentSong)
			var nextSongIndex = currentSongIndex - 1

			if (nextSongIndex < 0) {
				nextSongIndex = this.songOrder.length - 1
			}
			
			this.play(this.songOrder[nextSongIndex])
		}
	}

	pause() {
		audio.pause()
	}
}
