package game.mobs.states;

import openfl.Lib;
import openfl.events.Event;
import openfl.geom.Point;
import openfl.media.SoundChannel;

using Std;

class GhostChase extends MobState {
	var moveTimeTotal:Float = 0.5;
	var moveTime:Float = 0;

	var fromCellX:Int;
	var fromCellY:Int;

	var toCellX:Int;
	var toCellY:Int;

	var currentSound:SoundChannel;

	public function new(mob:Mob, screemSoundChannel:SoundChannel) {
		super(mob);
		chooseNextCell();

		currentSound = screemSoundChannel;
		currentSound.addEventListener(Event.SOUND_COMPLETE, nextSound);
	}

	function nextSound(event:Event) {
		if (Game.current.ghostSpawned) {
			currentSound = Game.current.playSound('assets/sound/ghost_${1 + Math.floor(6 * Math.random())}.ogg', 0, 0, mob.getSoundTransform());
			currentSound.addEventListener(Event.SOUND_COMPLETE, nextSound);
		}
	}

	function chooseNextCell() {
		fromCellX = mob.x.int();
		fromCellY = mob.y.int();

		var path = Game.current.pathToPlayer({cellX: fromCellX, cellY: fromCellY});

		if (path.length >= 2) {
			if (path.length >= 6) {
				currentSound.removeEventListener(Event.SOUND_COMPLETE, nextSound);
				Game.current.stopSound(currentSound);
				Game.current.endChase();
			} else {
				toCellX = path[1].cellX;
				toCellY = path[1].cellY;
			}
		} else {
			toCellX = Game.current.rc.camera.position.x.int();
			toCellY = Game.current.rc.camera.position.y.int();
		}

		moveTime = 0;
	}

	override function update(delta:Float) {
		if (mob.distance != null) {
			if (mob.distance <= 0.5) {
				Main.instance.setState(new Died());
				return;
			}

			mob.transformSound(currentSound);

			if (moveTime < moveTimeTotal) {
				mob.x = (fromCellX + (toCellX - fromCellX) * (moveTime / moveTimeTotal)) + 0.5;
				mob.y = (fromCellY + (toCellY - fromCellY) * (moveTime / moveTimeTotal)) + 0.5;

				moveTime += delta;

				if (moveTime >= moveTimeTotal) {
					mob.x = toCellX + 0.5;
					mob.y = toCellY + 0.5;

					chooseNextCell();
				}
			}
		}
	}
}
