const fs = require("fs")
const constants = require("../utils/constants");
const path = require("path");

const cacheNames = [ "video", "dearrow", "sb", "download", "ogg" ];
const cachesSaved = [ "video", "dearrow", "sb" ];
function getCachePath(cacheName) {
	return path.join(constants.server_setup.json_cache_path, `${cacheName}_cache.json`);
}

let caches = {}
try {
	for (let cache of cacheNames) {
		let cachePath = getCachePath(cache)
		if (cachesSaved.includes(cache)) {
			if (!fs.existsSync(cachePath))
				fs.writeFileSync(cachePath, "{}")
			caches[cache] = JSON.parse(fs.readFileSync(cachePath).toString())
		} else
			caches[cache] = {}
	}
} catch (error) {}

module.exports = {
	write: function(cacheName, key, value) {
		caches[cacheName][key] = value
	},
	read: function(cacheName) {
		return caches[cacheName]
	},
	clean: function(cacheName) {
		caches[cacheName] = {}
	}
}

// Save caches every hour
setInterval(() => {
	// Clear dearrow entries from videos
	for (const vidId in caches["video"]) {
		delete caches["video"][vidId].dearrowData
		for (const recVidId in caches["video"][vidId].recommendedVideos)
			delete caches["video"][vidId].recommendedVideos[recVidId].dearrowData
	}

	// Clear empty entries in dearrow cache
	for (const vidId in caches["dearrow"]) {
		let data = caches["dearrow"][vidId]
		if (!data.title && !data.thumbnail)
			delete caches["dearrow"][data]
	}

	// Save savable caches
	for (const cache of cachesSaved)
		fs.writeFileSync(getCachePath(cache), JSON.stringify(caches[cache]))

	// Clear download cache
	for (const vidName in caches["download"])
		if (caches["download"][vidName].status == 3)
			delete caches["download"][vidName]

	// Clear ogg cache
	for (const oggName in caches["ogg"])
		if (caches["ogg"][oggName].status == 2)
			delete caches["ogg"][oggName]
}, constants.server_setup.time_between_cache_save_to_disk)
