// Copyright (c) 2019, Christoph Peters
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Karlsruhe Institute of Technology nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


#include "TristimulusIntegrator.h"
#include "Grid3D.h"
#include "NearestNeighborIndex.h"
#include "colorSpaceConversion.h"
#include "XYZWarp.h"
#include <iostream>
#include <memory>
#include <utility>
#include <fstream>
#include <thread>
#include <string>

/*! Generates a grid of the given resolution covering the entire range of
	Fourier coefficients for reflectance spectra and fills it with the
	corresponding XYZ triples. mirrorSignal forwards to FourierSpectrum.*/
template<bool mirrorSignal>
std::unique_ptr<Grid3D> getFourierToXYZGrid(std::array<std::size_t, 3> resolution) {
	// Define integrator and wavelength mapping
	TristimulusIntegrator integrator = getXYZIntegrator(5);
	auto wavelengthToPhase = [](float wavelength, float& rOutPhase)->bool {
		if(mirrorSignal){
			rOutPhase = applyXYZWarpEven(wavelength);
		}
		else{
			rOutPhase = applyXYZWarpOdd(wavelength);
		}
		return (wavelength >= 360.0f && wavelength <= 830.0f);
	};
	// Initialize the grid
	std::unique_ptr<Grid3D> pResult;
	pResult.reset(new Grid3D(resolution, { 0.0f, -1.0f / 3.14159265358979f, -1.0f / 3.14159265358979f }, { 1.0f, 1.0f / 3.14159265358979f, 1.0f / 3.14159265358979f }));
	// Fill it with data
	pResult->fill(std::thread::hardware_concurrency(),
		[&integrator, &wavelengthToPhase](const std::array<float, 3>& rFourierCoefficients)->std::array<float, 3>
	{
		return integrator.integrate(FourierSpectrum<mirrorSignal, decltype(wavelengthToPhase)>(wavelengthToPhase, rFourierCoefficients));
	}
	);
	return pResult;
}


/*! Turns a grid such as the one produced by getFourierToXYZGrid() into an
	inverse grid mapping each XYZ triple to three Fourier coefficients. This is
	done by means of nearest neighbor lookups of the data in the given grid
	using the Euclidean norm in the CIELAB color space. Optionally, the output
	grid uses the sRGB color space instead of XYZ.*/
std::unique_ptr<Grid3D> getXYZToFourierGrid(std::array<std::size_t, 3> resolution, const Grid3D& rFourierToXYZGrid, bool useSRGB) {
	std::array<float, 3> cuboidMin = { 0.0f, 0.0f, 0.0f };
	std::array<float, 3> cuboidMax = { 1.0f, 1.0f, 1.0f };
	if (!useSRGB) {
		// Determine the maximal valid XYZ values by integrating the brightest 
		// reflectance spectrum
		TristimulusIntegrator integrator = getXYZIntegrator(1);
		cuboidMax = integrator.integrateConstantOne();
	}
	else {
		// For sRGB, we want to construct the lookup table such that quantized 
		// sRGB provides indices into the table. Commonly the smallest 
		// quantized value means 0.0 and the largest means 1.0, so we have to 
		// adapt the grid spacing.
		Grid3D::expandGrid(resolution, cuboidMin, cuboidMax);
	}
	// Define the grid
	std::unique_ptr<Grid3D> pResult;
	pResult.reset(new Grid3D(resolution, cuboidMin, cuboidMax));
	// Turn the XYZ in the source grid into CIELAB and prepare the lookup 
	// structure
	std::cout << "Converting XYZ to CIELAB..." << std::endl;
	const auto& rPointListXYZ = rFourierToXYZGrid.getData();
	std::vector<std::array<float, 3>> pointListLAB(rFourierToXYZGrid.getCellCount());
	std::transform(rPointListXYZ.begin(), rPointListXYZ.end(), pointListLAB.begin(), convertXYZToCIELAB);
	std::cout << "Building acceleration structure for nearest neighbor lookups..." << std::endl;
	NearestNeighborIndex nearestNeighborIndex(pointListLAB, { -1.0f, -1.0f, -1.0f });
	// Fill it with data
	std::cout << "Filling the output grid..." << std::endl;
	if(useSRGB){
		pResult->fill(std::thread::hardware_concurrency(),
			[&nearestNeighborIndex, &rFourierToXYZGrid](const std::array<float, 3>& rSRGBCoefficients)->std::array<float, 3>
		{
			std::size_t index = nearestNeighborIndex.query(convertXYZToCIELAB(convertSRGBToXYZ(rSRGBCoefficients, false)));
			return rFourierToXYZGrid.getDataCoordinate(rFourierToXYZGrid.unravelIndex(index));
		}
		);
	}
	else{
		pResult->fill(std::thread::hardware_concurrency(),
			[&nearestNeighborIndex, &rFourierToXYZGrid](const std::array<float, 3>& rXYZCoefficients)->std::array<float, 3>
		{
			std::size_t index = nearestNeighborIndex.query(convertXYZToCIELAB(rXYZCoefficients));
			return rFourierToXYZGrid.getDataCoordinate(rFourierToXYZGrid.unravelIndex(index));
		}
		);
	}
	return pResult;
}


int main(int nArgument, char* ppArgument[]) {
	std::size_t fourierToXYZResolution = 1024;
	std::size_t xyzToFourierResolution = 256;
	bool makeFourierToXYZGrid = true;
	bool useSRGB = true;
	std::string fourierToXYZFileName = "FourierToXYZ" + std::to_string(fourierToXYZResolution) + "Even.dat";
	std::string xyzToFourierFileName = std::string(useSRGB ? "SRGB" : "XYZ") + "ToFourier" + std::to_string(xyzToFourierResolution) + "Even.dat";
	if (makeFourierToXYZGrid) {
		auto pXYZToFourier = getFourierToXYZGrid<true>({ fourierToXYZResolution, fourierToXYZResolution, fourierToXYZResolution });
		std::ofstream outputStream(fourierToXYZFileName, std::ios_base::binary);
		pXYZToFourier->store(outputStream);
	}
	else {
		std::ifstream inputStream(fourierToXYZFileName, std::ios_base::binary);
		if (!inputStream.is_open()) {
			std::cout << "The input file " << fourierToXYZFileName << " could not be opened. Please generate it first." << std::endl;
			return 0;
		}
		std::cout << "Loading " << fourierToXYZFileName << "..." << std::endl;
		Grid3D fourierToXYZ(inputStream);
		auto pFourierToXYZ = getXYZToFourierGrid({ xyzToFourierResolution, xyzToFourierResolution, xyzToFourierResolution }, fourierToXYZ, useSRGB);
		std::cout << "Storing the grid to " << xyzToFourierFileName << "..." << std::endl;
		std::ofstream outputStream(xyzToFourierFileName, std::ios_base::binary);
		pFourierToXYZ->store(outputStream);
	}
	std::cout << "Done." << std::endl;
	return 0;
}
