import Sprite from '../sprite';
import FPS from '../fps';
import Hero from '../hero';

class UI {
	private timeLeft = 0;

	private fps = new FPS();

	constructor(private sprite: Sprite) {}

	drawTopBar(ctx: CanvasRenderingContext2D, hero: Hero, time: number) {
		ctx.fillStyle = 'black';
		ctx.beginPath();
		ctx.rect(0, 0, 128, 17);
		ctx.fill();

		ctx.strokeStyle = 'grey';
		ctx.beginPath();
		ctx.moveTo(0, 16);
		ctx.lineTo(128, 16);
		ctx.stroke();

		ctx.strokeStyle = 'silver';
		ctx.beginPath();
		ctx.moveTo(0, 16);
		ctx.lineTo(Math.round((hero.exp / hero.expForLevel) * 128), 16);
		ctx.stroke();

		ctx.fillStyle = 'white';

		const healthHalf = hero.health / 2;
		for (let i = 0; i < 3; i++) {
			const img =
				i < healthHalf - 0.5
					? 'ui_heart_full'
					: i === healthHalf - 0.5
					? 'ui_heart_half'
					: 'ui_heart_empty';

			this.sprite.draw(ctx, i * 16, 0, img);
		}

		ctx.font = '12px sans-serif';
		ctx.textAlign = 'center';
		ctx.fillText(`LVL ${hero.level}`, 70, 12);

		ctx.textAlign = 'right';
		const minutes = (time / 60000).toFixed(0).padStart(2, '0');
		const seconds = ((time % 60000) / 1000).toFixed(0).padStart(2, '0');
		ctx.fillText(`${minutes}:${seconds}`, 126, 12);
	}

	drawDead(ctx: CanvasRenderingContext2D, dt: number) {
		const maxTime = 2000;
		this.timeLeft = Math.min(this.timeLeft + dt, maxTime);
		const k = this.timeLeft / maxTime;

		ctx.fillStyle = `rgba(0,0,0, ${k / 2})`;
		ctx.beginPath();
		ctx.rect(0, 0, 128, 128);
		ctx.fill();

		ctx.font = `${(10 + 8 * k).toFixed(1)}px serif`;
		ctx.textAlign = 'center';
		ctx.fillStyle = `rgba(255,0,0,${k.toFixed(2)})`;
		ctx.fillText(`YOU DIED`, 64, 78);

		if (this.timeLeft >= maxTime) {
			ctx.font = `12px serif`;
			ctx.fillStyle = `white`;
			ctx.fillText(`SPACE TO RESTART`, 64, 110);
		}
	}

	drawFPS(ctx: CanvasRenderingContext2D) {
		return;
		this.fps.tick();
		ctx.fillStyle = 'white';
		ctx.font = '12px sans-serif';
		ctx.textAlign = 'left';
		ctx.fillText(this.fps.fps.toString(), 0, 128);
	}

	drawStart(ctx: CanvasRenderingContext2D) {
		ctx.font = `12px serif`;
		ctx.fillStyle = `white`;
		ctx.textAlign = 'center';
		ctx.fillText(`SPACE TO START`, 64, 64);
	}
}

export default UI;
