import fs from "node:fs"

const tryFiles = {
	name: 'tea:try-files',
	configureServer(server) {
		server.middlewares.use('/', (req, res, next) => {
			// try [ '/path_plus.html', '/path.html', '/path/index_plus.html', '/path/index.html']
			let urlPath = req.url
			let argsIndex = urlPath.indexOf("?")
			if (argsIndex >= 0) {
				urlPath = urlPath.substring(0, argsIndex)
			}

			if (urlPath == "/") {
				urlPath = "/views/index"
			} else {
				urlPath = "/views" + urlPath
			}

			if (urlPath.length > 0
				&& !urlPath.endsWith("/")
				&& urlPath.indexOf(":") < 0
				&& urlPath.indexOf("/@") < 0) {
				let pieces = urlPath.split("/")
				let lastPiece = pieces[pieces.length - 1]
				if (lastPiece.indexOf(".") < 0) {
					let candidateURLs = [
						urlPath + "_plus.html",
						urlPath + ".html",
						urlPath + "/index_plus.html",
						urlPath + "/index.html",
						urlPath + "_plus.vue",
						urlPath + ".vue",
						urlPath + "/index_plus.vue",
						urlPath + "/index.vue"
					]

					if (/[A-Z]/.test(urlPath)) {
						const newURLPath = urlPath.replace(/[A-Z]/, (c) => {
							return "-" + c.toLowerCase()
						})
						candidateURLs.push(...[urlPath + "_plus.html",
							newURLPath + ".html",
							newURLPath + "/index_plus.html",
							newURLPath + "/index.html",
							newURLPath + "_plus.vue",
							newURLPath + ".vue",
							newURLPath + "/index_plus.vue",
							newURLPath + "/index.vue"])
					}

					tryFiles.lookFiles(req, candidateURLs, next)
					return
				}
			}

			next()
		})
	},
	lookFiles(req, urls, next) {
		for (const url of urls) {
			try {
				fs.statSync(__dirname + "/.." + url)
				if (url.endsWith(".vue")) {
					req.url = "/views/layout.html"
				} else {
					req.url = url
				}
				next()
				return
			} catch (e) {
			}
		}
		next()
	}
}

export default tryFiles