import Screen from './screen';
import UI from './ui';
import Input from './input';
import { copy, multiply, normalize } from './vector';
import Room1 from './rooms';
import { DungeonSprite } from './sprites';
import World from './world';
import resources from './resources';
import Hero from './hero';
import Upgrade from './ui/upgrade';

resources
	.loadImage('dungeon', './images/0x72_DungeonTilesetII_v1.4.png')
	.then(() => {
		const dungeonSprite = new DungeonSprite();

		const input = new Input();

		const room = new Room1(dungeonSprite);

		const hero = new Hero(room.width / 2, room.height / 2);
		const world = new World(room, hero);

		const ui = new UI(dungeonSprite);
		const upgrade = new Upgrade(dungeonSprite);

		let t: number = 0;
		let timeLeft = 0;
		const screen = new Screen();

		let mode = 'start';

		screen.draw(
			(ctx, time) => {
				if (mode === 'play') {
					const dt = time - t;
					t = time;

					if (hero.health > 0) {
						const { newLevel } = world.update(dt);

						if (newLevel) {
							upgrade.reset();
							mode = 'upgrade';
						}

						const direction = normalize([
							input.left ? -1 : input.right ? 1 : 0,
							input.up ? -1 : input.down ? 1 : 0,
						]);
						const dir = multiply(copy(direction), hero.speed * dt);
						hero.move(world.move(hero, dir));

						timeLeft += dt;
					} else {
						if (input.enter) {
							world.reset();
							timeLeft = 0;
						}
					}

					ctx.save();
					ctx.translate(Math.round(-hero.x + 64), Math.round(-hero.y + 64));
					world.draw(ctx);
					ctx.restore();

					ui.drawFPS(ctx);

					ui.drawTopBar(ctx, hero, timeLeft);

					if (hero.health <= 0) {
						ui.drawDead(ctx, dt);
					}

					// drawCenter(ctx);
				} else if (mode === 'upgrade') {
					ui.drawFPS(ctx);
					ui.drawTopBar(ctx, hero, timeLeft);
					upgrade.draw(ctx);

					const selected = upgrade.update(input);
					if (selected) {
						world.upgradeWeapon(selected);
						mode = 'play';
						t = time;
					}
				} else if (mode === 'start') {
					ui.drawFPS(ctx);
					ui.drawTopBar(ctx, hero, timeLeft);
					ui.drawStart(ctx);

					if (input.enter) {
						mode = 'play';
						t = time;
					}
				}
			},
			(ctx, time, canvas) => {
				t = time;
				ctx.imageSmoothingQuality = 'low';
				ctx.imageSmoothingEnabled = false;
				canvas.width = 128;
				canvas.height = 128;
			},
		);
	});

const drawCenter = (ctx: CanvasRenderingContext2D) => {
	ctx.fillStyle = 'red';
	ctx.beginPath();
	ctx.arc(64, 64, 1, 0, 2 * Math.PI, false);
	ctx.fill();
};
