package game.obj;

import game.mobs.Ghost;
import game.mobs.states.GhostChase;
import openfl.Lib;
import openfl.events.Event;
import openfl.media.SoundChannel;
import openfl.media.SoundTransform;

using Std;

class GhostSpawn extends GameSprite {
	var soundTime:Float = 0;

	static final START_CHASE_DISTANCE:Int = 3;

	var playerCellX:Null<Int> = null;
	var playerCellY:Null<Int> = null;

	var currentSound:SoundChannel;

	var soundPlaying:Bool = false;

	public function new(?x:Float, ?y:Float) {
		super(null, x, y);
	}

	override function update(delta:Float) {
		if (Game.current.canSpawnGhost
			&& !Game.current.ghostSpawned
			&& (Game.current.chaseEndTime == null || Lib.getTimer() - Game.current.chaseEndTime >= 5000)) {
			var currentPlayerX:Int = raycaster.camera.position.x.int();
			var currentPlayerY:Int = raycaster.camera.position.y.int();

			if (playerCellX != currentPlayerX || playerCellY != currentPlayerY) {
				playerCellX = currentPlayerX;
				playerCellY = currentPlayerY;

				var path = Game.current.pathToPlayer({cellX: x.int(), cellY: y.int()});

				if (path.length == START_CHASE_DISTANCE) {
					if (currentSound != null) {
						currentSound.stop();
						currentSound = null;
						soundPlaying = false;
					}

					var ghost = new Ghost(x, y);
					ghost.state = new GhostChase(ghost, Game.current.playSound('assets/sound/ghost_scream.ogg', getSoundTransform()));
					Game.current.rc.addSprite(ghost);
					Game.current.startChase();
					Game.current.ghostSpawned = true;
					Game.current.currentGhost = ghost;
					return;
				}
			}
		} else {
			if (!soundPlaying && distance != null && soundTime <= 0) {
				if (distance < GameSprite.SOUND_DISTANCE) {
					currentSound = Game.current.playSound('assets/sound/ghost_${1 + Math.floor(6 * Math.random())}.ogg', getSoundTransform());
					soundPlaying = true;
					currentSound.addEventListener(Event.SOUND_COMPLETE, (event:Event) -> {
						currentSound = null;
						soundPlaying = false;
					});

					soundTime = 5 + 10 * Math.random();
				}
			} else
				soundTime -= delta;
		}
	}
}
