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


// find all images
const slug = process.env["PACKAGE_NAME"];
console.log(slug);
const root = process.env["ENTRY_FOLDER"];
console.log(root);
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));
		//if (err) { throw err };
		// extract metadata
		let metadata = iptc(buffer);
		// fill object
		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 ||= metadata.original_transmission_reference;
					break;
				case "nightHighlight":
					theme.nightHighlight ||= metadata.original_transmission_reference;
					break;
				default:
					break;
			}
		});

		switch (metadata.category) {
			case "day":
				theme.dayImageList.push(metadata.original_transmission_reference);
				break;
			case "night":
			case "nig":
				theme.nightImageList.push(metadata.original_transmission_reference);
				break;
			case "sunset":
			case "twilight":
			case "twi":
				theme.sunsetImageList.push(metadata.original_transmission_reference);
				break;
			case "sunrise":
			case "dawn":
			case "daw":
				theme.sunriseImageList.push(metadata.original_transmission_reference);
				break;
			default:
				break;
		}
	});

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




