const fs = require("fs");
const path = require("path");
const iptc = require("node-iptc");
const { exit } = require("process");


// Fetch envs to target the right folder
const slug = process.env["PACKAGE_NAME"];
const root = process.env["ENTRY_FOLDER"];
if (!slug || !root) exit(1);
let workingDirectory = path.join(root, slug);

// extract metadata from them
fs.readdir(workingDirectory, (err, files) => {
	if (err) { throw err };	// If IO error, exit with an error message

	// If there is already a theme.json silentely exit and let mocha running afterwards
	if (!files.find(file => path.extname(file) == '.json')) exit(0);

	// construct a JSON object
	let theme = new Object();
	theme.dayImageList = [];
	theme.nightImageList = [];
	theme.sunsetImageList = [];
	theme.sunriseImageList = [];

	// iterate each files
	files.filter(file => path.extname(file) == '.jpg').forEach(image => {
		buffer = fs.readFileSync(path.join(workingDirectory, image));
		// extract metadata
		let metadata = iptc(buffer);
		theme.imageFilename ||= metadata.special_instructions + "_*" + path.extname(image);
		theme.imageCredits ||= metadata.copyright_notice;
		theme.displayName ||= metadata.headline;
		// explore categories to find if image is dayHighlight or nightHighlight
		metadata.supplemental_categories?.forEach(cat => {
			switch (cat) {
				case "dayHighlight":
					theme.dayHighlight ||= parseInt(metadata.original_transmission_reference);
					break;
				case "nightHighlight":
					theme.nightHighlight ||= parseInt(metadata.original_transmission_reference);
					break;
				default:
					break;
			}
		});

		switch (metadata.category) {
			case "day":
				theme.dayImageList.push(parseInt(metadata.original_transmission_reference));
				break;
			case "night":
			case "nig":
				theme.nightImageList.push(parseInt(metadata.original_transmission_reference));
				break;
			case "sunset":
			case "twilight":
			case "twi":
				theme.sunsetImageList.push(parseInt(metadata.original_transmission_reference));
				break;
			case "sunrise":
			case "dawn":
			case "daw":
				theme.sunriseImageList.push(parseInt(metadata.original_transmission_reference));
				break;
			default:
				break;
		}
	});
	// make it the theme.json
	fs.writeFileSync(path.join(workingDirectory, 'theme.json'), JSON.stringify(theme));
});




