class SongCacher {
	constructor() {
		this.cancelled = false
	}

	cacheAll() {
		this.run(assets.songs)
	}

	cacheCategory(categoryId) {
		var songs = assets.songs.filter(song => song.category_id === categoryId)
		this.run(songs)
	}

	cacheSong(songId) {
		var songs = assets.songs.filter(song => song.id === songId)
		this.run(songs)
	}

	async run(songs) {
		if (!confirm(strings.cache.cacheConfirm)) {
			return
		}
		
		this.cancelled = false
		var total = songs.length
		var current = 0
		
		var loaderDiv = document.createElement("div")
		loaderDiv.style.position = "fixed"
		loaderDiv.style.top = "0"
		loaderDiv.style.left = "0"
		loaderDiv.style.width = "100%"
		loaderDiv.style.height = "100%"
		loaderDiv.style.backgroundColor = "rgba(0,0,0,0.8)"
		loaderDiv.style.zIndex = "10000"
		loaderDiv.style.color = "white"
		loaderDiv.style.display = "flex"
		loaderDiv.style.justifyContent = "center"
		loaderDiv.style.alignItems = "center"
		loaderDiv.style.fontSize = "24px"
		loaderDiv.style.flexDirection = "column"
		
		var text = document.createElement("div")
		loaderDiv.appendChild(text)
		
		var cancelBtn = document.createElement("button")
		cancelBtn.innerText = strings.cancel
		cancelBtn.style.marginTop = "20px"
		cancelBtn.style.padding = "10px 20px"
		cancelBtn.style.fontSize = "20px"
		cancelBtn.onclick = () => {
			this.cancelled = true
			document.body.removeChild(loaderDiv)
		}
		loaderDiv.appendChild(cancelBtn)
		
		document.body.appendChild(loaderDiv)
		
		for (let song of songs) {
			if (this.cancelled) break
			current++
			text.innerText = strings.cache.cacheProgress.replace("%s", current).replace("%s", total) + "\n" + song.title
			
			try {
				if (song.music) {
					await song.music.blob()
				}
				if (song.chart && song.chart.read) {
					await song.chart.read()
				}
			} catch (e) {
				console.error(e)
			}
		}
		
		if (!this.cancelled) {
			document.body.removeChild(loaderDiv)
			alert(strings.cache.cacheComplete)
		}
	}
}
