const {Pinski} = require("pinski")
const {setInstance} = require("pinski/plugins")
const constants = require("./utils/constants")
const iconLoader = require("./utils/icon-loader").icons
const path = require("path")
const fs = require("fs")

;(async () => {
	// Create directories
	if (!fs.existsSync(constants.server_setup.video_dl_path))
		fs.mkdirSync(constants.server_setup.video_dl_path, { recursive: true })
	if (!fs.existsSync(constants.server_setup.ogg_dl_path))
		fs.mkdirSync(constants.server_setup.ogg_dl_path, { recursive: true })
	if (!fs.existsSync(constants.server_setup.json_cache_path))
		fs.mkdirSync(constants.server_setup.json_cache_path, { recursive: true })
	if (!fs.existsSync(constants.server_setup.ytdlp_cache_path))
		fs.mkdirSync(constants.server_setup.ytdlp_cache_path, { recursive: true })

	await require("./utils/upgradedb")()
	const icons = await iconLoader

	const server = new Pinski({
		port: 10412,
		relativeRoot: __dirname,
		filesDir: "html"
	})

	setInstance(server)
	server.pugDefaultLocals.constants = constants
	server.pugDefaultLocals.icons = icons
	server.pugDefaultLocals.isMobile = req => req.headers["user-agent"].match(/phone|mobile/i)

	server.muteLogsStartingWith("/watch")
	server.muteLogsStartingWith("/vi/")
	server.muteLogsStartingWith("/favicon")
	server.muteLogsStartingWith("/static")

	server.addSassDir("sass", ["sass/includes", "sass/themes", "sass/theme-modules"])
	server.addRoute("/static/css/dark.css", "sass/dark.sass", "sass")
	server.addRoute("/static/css/light.css", "sass/light.sass", "sass")
	server.addRoute("/static/css/edgeless-light.css", "sass/edgeless-light.sass", "sass")
	server.addRoute("/static/css/eir.css", "sass/eir.sass", "sass")

	server.addPugDir("pug", ["pug/includes"])
	server.addPugDir("pug/errors")

	server.addStaticHashTableDir("html/static/js")
	server.addStaticHashTableDir("html/static/js/elemjs")
	server.addStaticHashTableDir("html/static/images")
	server.addStaticHashTableDir("html/static/fonts")

	server.addAPIDir("api")

	// Special paths. DO NOT INCLUDE video cache location, or pinski watcher will lag downloads
	//   - Eir
	server.muteLogsStartingWith("/assets")
	server.muteLogsStartingWith("/getVideo")
	server.muteLogsStartingWith("/getCaption")
	server.muteLogsStartingWith("/getOgg")
	server.muteLogsStartingWith("/redownloadVideo")
	server.muteLogsStartingWith("/cacheInfo")
	server.muteLogsStartingWith("/getDeArrow")

	server.startServer()

	require("./background/feed-update")
	// Keep cache under a certain size.
	//   - Eir
	require("./background/cache-reaper")
	require("./eirtubeMods/dl-queue")
})()
