#include "AnimationInterpolate.h"
#include "AnimationObject.h"
#include "AnimationMove.h"
#include <string.h>

#define NUM_INTERPOLATE(a, b, perc) (a * (1.0 - (perc)) + b * (perc))

color
colorInterpolate(color ina, color inb, double percentage) {
	ARGB a, b;
	ARGB_set(&a, ina);
	ARGB_set(&b, inb);

	a.a = NUM_INTERPOLATE(a.a, b.a, percentage);
	a.r = NUM_INTERPOLATE(a.r, b.r, percentage);
	a.g = NUM_INTERPOLATE(a.g, b.g, percentage);
	a.b = NUM_INTERPOLATE(a.b, b.b, percentage);

	return a.a << 24 | a.r << 16 | a.g << 8 | a.b;
}

ARGB
A_Interpolate(const Animation* anim, u32 frameIndex, ARGB pixel, i32 r, i32 c, void* value) {
	struct A_Interpolate in = *(struct A_Interpolate*)value;

	if (in.interpolate == NULL) {
		fprintf(stderr, "Interpolation function cannot be NULL!\n");
		ARGB_set(&pixel, 0xFFFF00FF);
		return pixel;
	}

	if (frameIndex == in.startFrame) {
		memcpy(in.initialValueTemp, in.value, in.initialValueTempSize);
	}

	double perc = (double)(frameIndex - in.startFrame) / (in.endFrame - in.startFrame);
	if (perc < 0.0) perc = 0.0;
	if (perc > 1.0) perc = 1.0;

	in.interpolate(in.value, in.initialValueTemp, in.goalValue, perc);

	return pixel;
}

void
AO_LineInterpolate(void* valueLine, const void* initialLine, const void* finalLine, double percentage) {
	struct AO_Line* value = valueLine;
	const struct AO_Line* initial = initialLine, *final = finalLine;

	value->a = NUM_INTERPOLATE(initial->a, final->a, percentage);
	value->b = NUM_INTERPOLATE(initial->b, final->b, percentage);
	value->c = NUM_INTERPOLATE(initial->c, final->c, percentage);
	value->width = NUM_INTERPOLATE(initial->width, final->width, percentage);
	value->color = colorInterpolate(initial->color, final->color, percentage);
}

void
AM_LinearInterpolate(void* valueIn, const void* initialIn, const void* finalIn, double percentage) {
	struct AM_Linear* value = valueIn;
	const struct AM_Linear* initial = initialIn, *final = finalIn;

	value->startRow = NUM_INTERPOLATE(initial->startRow, final->startRow, percentage);
	value->startCol = NUM_INTERPOLATE(initial->startCol, final->startCol, percentage);
	value->dRow = NUM_INTERPOLATE(initial->dRow, final->dRow, percentage);
	value->dCol = NUM_INTERPOLATE(initial->dCol, final->dCol, percentage);
	value->wrapCoordinates = NUM_INTERPOLATE(initial->wrapCoordinates, final->wrapCoordinates, percentage);
}

void
AM_SpinInterpolate(void* valueIn, const void* initialIn, const void* finalIn, double percentage) {
	struct AM_Spin* value = valueIn;
	const struct AM_Spin* initial = initialIn, *final = finalIn;

	value->theta = NUM_INTERPOLATE(initial->theta, final->theta, percentage);
	value->dTheta = NUM_INTERPOLATE(initial->dTheta, final->dTheta, percentage);
	value->centerRow = NUM_INTERPOLATE(initial->centerRow, final->centerRow, percentage);
	value->centerCol = NUM_INTERPOLATE(initial->centerCol, final->centerCol, percentage);
}
