#include "ColorGradient.h"

ColorGradient::ColorGradient(float min, float max, vector<RGBA> colorSteps)
{
	_minValue = min;
	_maxValue = max;
	_colorSteps = colorSteps;
}

ColorGradient::~ColorGradient()
{
	_colorSteps.clear();
}

// Get the RGBA value at the give point 
RGBA ColorGradient::GetRGBAValue(float inputValue)
{
	// Check if we are at the start or end, return those values if so
	if (inputValue <= _minValue)
	{
		return _colorSteps.front();
	}
	else if (inputValue >= _maxValue)
	{
		return _colorSteps.back();
	}
	
	// Get the point which the input value is at between the entire range
	float range = _maxValue - _minValue;
	float value = inputValue - _minValue;
	float steps = range / (float)(_colorSteps.size() - 1);
	
	// Which gradient step are we in
	int colorStepInside = (int)(value / steps);

	float normalisedValue = (value - (colorStepInside * steps)) / steps;

	return Interpolate(_colorSteps[colorStepInside], _colorSteps[colorStepInside + 1], normalisedValue);
}

// Method for interpolating the color between each step
RGBA ColorGradient::Interpolate(RGBA a, RGBA b, float pointValue)
{
	// Check if we are at the start or end, return those values if so
	if (pointValue <= 0.0f)
	{
		return a;
	}
	else if (pointValue >= 1.0f)
	{
		return b;
	}

	//pointValue = SharedMethods::Clamp<float>(pointValue * 1.5f, 0.0f, 1.0f);

	// Lerp the color values for each channel between the steps
	unsigned int currentRed = (unsigned int)SharedMethods::Lerp<unsigned int>(a.red, b.red, pointValue);
	unsigned int currentGreen = (unsigned int)SharedMethods::Lerp<unsigned int>(a.green, b.green, pointValue);
	unsigned int currentBlue = (unsigned int)SharedMethods::Lerp<unsigned int>(a.blue, b.blue, pointValue);
	unsigned int currentAlpha = (unsigned int)SharedMethods::Lerp<unsigned int>(a.alpha, b.alpha, pointValue);

	return RGBA{ currentRed, currentGreen, currentBlue, currentAlpha };
}