/** @module file-script-handler/imageDimensionsHandler */
'use strict';

const im = require('imagemagick');
const imageDimensionsHandler = exports;
const logger = require('dachshund-logger').getLogger(__filename);
const repositoryManager = require('repository-manager');

const extractMetadata = function(metadata) {
	let metadataObject = {
		type: "",
		dimensions: "",
		width: 0,
		height: 0,
		sizeInBytes: 0
	};

	let metadataParts = metadata.split(" ");

	try
	{
		metadataObject.sizeInBytes = parseInt(metadataParts[0].substring(0, metadataParts[0].length - 1));
		metadataObject.type = metadataParts[1];
		metadataObject.width = parseInt(metadataParts[2]);
		metadataObject.height = parseInt(metadataParts[3]);
		metadataObject.dimensions = metadataObject.width + "x" + metadataObject.height;
	} catch (ex)
	{
		logger.error("Error while transforming image metadata: " + ex);
	}

	return metadataObject;
};

imageDimensionsHandler.test = function(pathInfo) {
	let extension = pathInfo.extension.toLowerCase();

	if (pathInfo.selector === null)
	{
		return false;
	}

	let selectorParts = pathInfo.selector.split(".");
	if (selectorParts.length < 2)
	{
		return false;
	}

	let secondLastSelector = selectorParts[selectorParts.length - 2].toLowerCase();
	let lastSelector = selectorParts[selectorParts.length - 1].toLowerCase();

	return lastSelector === "dimensions" && (secondLastSelector === "png" || secondLastSelector === "gif" || secondLastSelector === "jpg" || secondLastSelector === "jpeg") && extension === "json";
};

imageDimensionsHandler.handle = async function(req, resp, pathInfo, resource) {
	try
	{


		let selectorParts = pathInfo.selector.split(".");

		//Remove the "dimensions" from the selector list
		selectorParts.splice(selectorParts.length - 1, 1);

		if (selectorParts.length > 2 && selectorParts[selectorParts.length - 3] === "min" || selectorParts[selectorParts.length - 3] === "max")
		{
			selectorParts.splice(selectorParts.length - 3, 1);
		}

		if (selectorParts.length > 1 && selectorParts[selectorParts.length - 2].contains("x"))
		{
			selectorParts.splice(selectorParts.length - 2, 1);
		}
		let selector = selectorParts.join(".");

		let naturalImagePath = pathInfo.componentPath + "." + selector;
		let resource = await repositoryManager.resolve(naturalImagePath);
		let imagePath = resource.source || naturalImagePath;

		let metadata = await new Promise((resolve, reject) => {
			im.identify("-format", "%b %m %w %h", process.cwd() + imagePath, (err, metadata) => {
				if (err)
				{
					reject(err);
				}
				else
				{
					resolve(metadata);
				}
			});
		});

		let metadataObject = extractMetadata(metadata);
		metadataObject.imagePath = naturalImagePath;
		resp.writeHead(200, {"Content-Type": "application/json; charset=utf-8"});
		resp.write(JSON.stringify(metadataObject));
		resp.end();

	} catch (err)
	{
		resp.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
		resp.write("Error while reading image dimensions " + err);
		resp.end();
	}

};