const fs = require('fs');
const path = require('path');
const YAML = require('yaml');

const openapiYAML = path.join(__dirname, "../../../spec/openapi.yaml");
const openapiHTML = path.join(__dirname, "../../../spec/openapi.html");

module.exports = async function (req, res, next) {

	function handleError (err) {
		if (err instanceof TypeError || err.code == "ENOENT") {
			res.status(404).send();
			next();
		} else {
			next(err);
		}
	}

	try {
		if (req.accepts("text/html")) {
			const stream = fs.createReadStream(openapiHTML);
			stream.on('open', () => {
				res.set("Content-Type", "text/html");
				stream.pipe(res);
			});
			stream.on('end', next);
			stream.on('error', handleError);
		} else if (req.accepts("application/json")) {
			const text = await fs.promises.readFile(openapiYAML, 'utf8');
			res.json(YAML.parse(text));
			next();
		} else {
			const stream = fs.createReadStream(openapiYAML);
			stream.on('open', () => {
				res.set("Content-Type", "application/yaml");
				stream.pipe(res);
			});
			stream.on('end', next);
			stream.on('error', handleError);
		}
	} catch (err) {
		handleError(err);
	}
};
