#include "DeathAnimation.h"

DeathAnimation::DeathAnimation(PixelGameEngine*pge,vf2d pos,Renderable&unitImg,Renderable&matrixImg,bool friendly)
:pos(pos),matrixImg(matrixImg),originalImg(unitImg),friendly(friendly),randomOffset(rand()%168,rand()%168){
	img.Create(unitImg.Sprite()->width,unitImg.Sprite()->height);
	pge->SetDrawTarget(img.Sprite());
	pge->DrawSprite({0,0},unitImg.Sprite());
	pge->SetDrawTarget(nullptr);
	img.Decal()->Update();
}
void DeathAnimation::Update(float fElapsedTime){
	fadeTimer=std::max(0.f,fadeTimer-fElapsedTime);
}
void DeathAnimation::Draw(TileTransformedView&game,PixelGameEngine*pge){
	pge->SetDrawTarget(img.Sprite());
	pge->Clear(BLANK);
	for(int y=0;y<img.Sprite()->height;y++){
		for(int x=0;x<img.Sprite()->width;x++){
			Pixel col=originalImg.Sprite()->GetPixel(x,y);
			if(col.a==255&&col.r<=(fadeTimer/CONSTANT::DEATH_FADE_TIME)*255){
				pge->Draw(x,y,matrixImg.Sprite()->GetPixel(x+randomOffset.x,y+randomOffset.y));
			} else {
				pge->Draw(x,y,originalImg.Sprite()->GetPixel(x+randomOffset.x,y+randomOffset.y));
			}
		}
	}
	img.Decal()->Update();
	pge->SetDrawTarget(nullptr);
	game.DrawRotatedDecal(pos,img.Decal(),0,img.Sprite()->Size()/2,{1,1},friendly?Pixel{192,192,255,uint8_t((fadeTimer/CONSTANT::DEATH_FADE_TIME)*255)}:Pixel{255,192,192,uint8_t((fadeTimer/CONSTANT::DEATH_FADE_TIME)*255)});
}

bool DeathAnimation::IsDone(){
	return fadeTimer==0;
}