import flixel.math.FlxMath;

import backend.ClientPrefs;

import flixel.math.FlxRect;
import flixel.FlxSprite;

var warpShader = createRuntimeShader('heatShader');
var healthCover;
var fakeHealth = game.health;

function onCreatePost()
{
	iconP1.visible = false;
	iconP2.visible = false;
	timeBar.visible = false;
	timeTxt.visible = false;
	
	var border = new FlxSprite(0, 0, Paths.image('ui/uiBorder'));
	border.antialiasing = ClientPrefs.data.antialiasing;
	uiGroup.add(border);
	
	healthBar.bg.loadGraphic(Paths.image('ui/uiHealthBar-Boarder'));
	healthBar.leftBar.makeGraphic(healthBar.bg.width, healthBar.bg.height); // fixes
	healthBar.rightBar.makeGraphic(healthBar.bg.width, healthBar.bg.height);
	healthBar.barWidth = 656;
	healthBar.barHeight = 19;
	healthBar.barOffset.set(23, 3);
	healthBar.screenCenter(1);
	
	healthBar.valueFunction = () -> fakeHealth;
	
	scoreTxt.font = Paths.font('Hellios-Gothic.ttf');
	scoreTxt.borderSize = 2;
	scoreTxt.size = 24;
	
	scoreTxt.y = healthBar.y + healthBar.height;
	
	healthCover = new FlxSprite(0, 0, Paths.image('ui/healthCover'));
	healthBar.insert(healthBar.members.indexOf(healthBar.leftBar) + 1, healthCover);
	
	border.shader = warpShader;
	border.blend = 9;
	
	updateHealthColours();
}

var time:Float = 0;

function onUpdatePost(e)
{
	time += e * 0.5;
	warpShader.setFloat('iTime', time);
	
	var newX = healthBar.barCenter - healthCover.width + 1;
	
	if (healthCover.x != newX)
	{
		healthCover.x = newX;
		
		if (healthCover.clipRect == null) healthCover.clipRect = new FlxRect(0, 3, healthCover.frameWidth, healthCover.frameHeight);
		
		if (healthCover.x < healthBar.x + healthBar.barOffset.x)
		{
			var xDiff = (healthBar.x + healthBar.barOffset.x) - healthCover.x;
			
			healthCover.clipRect.set(xDiff, 3, healthCover.frameWidth - xDiff, healthCover.frameWidth);
		}
		else
		{
			healthCover.clipRect.set(0, 3, healthCover.frameWidth, healthCover.frameHeight);
		}
		
		healthCover.clipRect = healthCover.clipRect;
	}
	
	fakeHealth = FlxMath.lerp(fakeHealth, health, 1 - Math.exp(-e * 24));
}

function onEvent(ev, v1, v2, time)
{
	updateHealthColours();
}

function updateHealthColours()
{
	var playerColour = FlxColor.fromRGB(boyfriend.healthColorArray[0], boyfriend.healthColorArray[1], boyfriend.healthColorArray[2]);
	
	if (healthCover != null) healthCover.color = playerColour;
}
