const fs = require("fs");
const path = require("path");
const iptc = require("node-iptc");


// find all images
const slug = process.env["PACKAGE_NAME"];
const root = process.env["ENTRY_FOLDER"];
let workingDirectory = path.join(root, slug);

// extract metadata from them
fs.readdir(workingDirectory, (err, files) => {
	if (err) { throw err };

	// construct a JSON file
	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;
		}
	});

	fs.writeFileSync(path.join(workingDirectory, 'theme.json'), JSON.stringify(theme));
});




