const fr = require('face-recognition')

if (process.argc <= 2) {
	console.log("Usage: node face image");
	process.exit(-1);
}

const filename = process.argv[2];

console.log("Loading " + filename);
const image = fr.loadImage(filename)
const detector = fr.FaceDetector()

console.log("Detecting faces...");
const faceRectangles = detector.locateFaces(image)
if (faceRectangles.length == 0) {
	console.log("No faces found.");
	process.exit(-1);
}

/* 200x200 picture faces */
const faceImages = detector.detectFaces(image, 200)
console.log("Writing " + faceImages.length + " faces.");

const fs = require("fs"),
	path = require("path");
const filepath = path.dirname(filename) + "/faces";
try {
	fs.statSync(filepath);
} catch (error) {
	fs.mkdirSync(filepath);
}

faceImages.forEach(function(face, index) {
	let target = filepath + "/" + path.basename(filename).replace(/.(png|jpg|jpeg)$/, "-face-" + (index + 1));
	faceRectangles[index].filename = filename;
	fs.writeFileSync(target + ".nfo", JSON.stringify(faceRectangles[index], null, 2));
	fr.saveImage(target + ".png", face);
});
