using Godot;
using System;
using Godot.Collections;

[Tool]
public partial class NPC : Node2D
{
	[Signal]
	public delegate void DialogEndedEventHandler();
	
	[Export] public string NPCName;
	[Export] public SpriteFrames Frames;
	[Export] public string DefaultDialogLine;
	[Export] public Array<string> DialogLines = new Array<string>();

	public bool Flip
	{
		get => _sprite.FlipH;
		set => _sprite.FlipH = value;
	}

	private AnimatedSprite2D _sprite;
	private Interactable _interactable;
	private int _currentDialogLine;

	//Диалог закончен, если больше нет строк диалога.
	public bool IsDialogEnded => _currentDialogLine == DialogLines.Count;

	//Возвращаем строку диалога и увеличиваем счетчик текущей строки если диалог законче, и возвращаем строку по-умолчанию, если диалог законен.
	public string Message
	{
		get
		{
			if (_currentDialogLine + 1 == DialogLines.Count)
			{
				EmitSignal(SignalName.DialogEnded);
			}
			return IsDialogEnded ? DefaultDialogLine : DialogLines[_currentDialogLine++];
		}
	}

	public void Disable()
	{
		_interactable.Disable();
	}

	public void Enable()
	{
		_interactable.Enable();
	}
	
	public override void _Ready()
	{
		_sprite = (AnimatedSprite2D)FindChild("AnimatedSprite2D");
		_interactable = (Interactable)FindChild("Interactable");
		if (Frames is not null) _sprite.SpriteFrames = Frames;
		_sprite.Play("default");
		_currentDialogLine = 0;
	}

	public override void _Process(double delta)
	{
	}

	public override void _PhysicsProcess(double delta)
	{
		if (Engine.IsEditorHint())
		{
			if (Frames is not null && _sprite.SpriteFrames != Frames) _sprite.SpriteFrames = Frames;
		}
	}

	private void _on_interactable_player_near_by(Player player)
	{
		player.InteractableObjects.Add(this);
	}


	private void _on_interactable_player_left(Player player)
	{
		player.InteractableObjects.Remove(this);
	}
}
