package game.obj;

import game.tiles.DestructableTile;
import lime.ui.Gamepad;
import openfl.media.SoundChannel;
import openfl.media.SoundTransform;
import openfl.utils.Assets;

class Bomb extends AnimSprite {
	var totalTime:Float;
	var time:Float;
	var fuseSound:SoundChannel;

	public function new(?x:Float, ?y:Float, ?time:Float = 2) {
		super('assets/sprites/bomb.aseprite', x, y);

		fuseSound = Game.current.playSound('assets/sound/fuse.ogg');
		this.totalTime = this.time = time;
	}

	override function update(delta:Float) {
		var distFactor:Float = (20 - distance) / 20;
		if (time <= 0) {
			Game.current.shake(1 * distFactor, 1);

			var transform = new SoundTransform(1 * distFactor, (16 - screenX) / 32);

			Game.current.stopSound(fuseSound);
			Game.current.playSound('assets/sound/explosion.ogg', transform);

			raycaster.addSprite(new Explosion(x, y));
			raycaster.removeSprite(this);

			var cellX = Std.int(x);
			var cellY = Std.int(y);

			var cells:Array<{cellX:Int, cellY:Int}> = [
				{cellX: cellX - 1, cellY: cellY},
				{cellX: cellX + 1, cellY: cellY},
				{cellX: cellX, cellY: cellY - 1},
				{cellX: cellX, cellY: cellY + 1}
			];

			for (cell in cells) {
				var tile = Game.current.map.getTile(cell.cellX, cell.cellY);

				if (tile != null && tile.collision) {
					var mapTile = Game.current.map.tiles[cell.cellX][cell.cellY];

					if (Std.is(mapTile, DestructableTile)) {
						cast(mapTile, DestructableTile).hit();
					}
				}
			}
		} else {
			var newVol = 1 * distFactor;

			if (fuseSound.soundTransform.volume != newVol) {
				var transform = new SoundTransform(newVol);
				fuseSound.soundTransform = transform;
			}

			if (time > 1) {
				var maxFrames:Int = aseprite.tags['burn'].chunk.toFrame;
				aseprite.currentFrame = Math.floor(maxFrames * (time - 1) / (totalTime - 1));
			} else {
				aseprite.play('critical');
			}
			time -= delta;
		}

		super.update(delta);
	}
}
