using Godot;
using System;

public partial class Day1Cutscene : Node2D
{
	[Signal]
	public delegate void FinishedEventHandler();
	
	private Player _player;

	private AnimatedSprite2D _sprite;
	
	private NPC _npc1;

	private NPC _npc2;

	private AudioStreamPlayer _spook;
	private AudioStreamPlayer _doorSounds;

	private bool _stage4 = false;

	private double _captainLeaveTime = 0;

	private Vector2 _spriteInitialPosition;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		_sprite = (AnimatedSprite2D)FindChild("AnimatedSprite2D");
		_npc1 = (NPC)FindChild("NPC1");
		_npc2 = (NPC)FindChild("NPC2");
		_spook = (AudioStreamPlayer)FindChild("Spook");
		_doorSounds = (AudioStreamPlayer)FindChild("DoorSounds");
		_spriteInitialPosition = _sprite.GlobalPosition;
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		if (_stage4)
		{
			if (_captainLeaveTime <= 3)
			{
				if (_sprite.Animation == "default") _sprite.Play("walk");
				_captainLeaveTime += delta;
				_sprite.GlobalPosition =
					_spriteInitialPosition.Lerp(new Vector2(1179, _sprite.GlobalPosition.Y), (float)(_captainLeaveTime / 3));
			}
			else
			{
				_stage4 = false;
				_sprite.Visible = false;
				_doorSounds.Play();
			}
			
		}
	}

	public void Final()
	{
		_player.CurrentState = Player.State.Normal;
		EmitSignal(SignalName.Finished);
		QueueFree();
	}
	
	public void Stage1(Node2D body)
	{
		if (body is Player player)
		{
			_player = player;
			player.InteractableObjects.Add(_npc1);
			player.CurrentState = Player.State.ChatWithNPC;
			player.AddMessage(_npc1);
		}
	}

	public void Stage2()
	{
		_player.CurrentState = Player.State.Wait;
		_player.InteractableObjects.Remove(_npc1);
		AudioServer.SetBusVolumeDb(1, -20);
		_spook.Play();
		_player.InteractableObjects.Add(_npc2);
	}

	public void Stage3()
	{
		_sprite.FlipH = true;
		AudioServer.SetBusVolumeDb(1, 0);
		_player.CurrentState = Player.State.ChatWithNPC;
		_player.AddMessage(_npc2);
	}

	public void Stage4()
	{
		_player.InteractableObjects.Remove(_npc2);
		_stage4 = true;
		_player.CurrentState = Player.State.Wait;
	}
}
