using Godot;
using System;

public partial class DialogueBoxSide : Control
{

	private TextBoxDialogue res;

	// CHILDS
	private Button progress;
	private RichTextLabel current;
	private ScrollContainer scroll;
	private VScrollBar vScrollBar;
	private VBoxContainer oldTextContainer;

	private int i = 0;
	private int maxScrollValue = 0;

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		progress = GetNode<Button>("PanelContainer/MarginContainer/VBoxContainer/MarginContainer/Progress");
		current = GetNode<RichTextLabel>("PanelContainer/MarginContainer/VBoxContainer/CurrentParagraph");
		scroll = GetNode<ScrollContainer>("PanelContainer/MarginContainer/VBoxContainer/ScrollContainer");
		oldTextContainer = GetNode<VBoxContainer>("PanelContainer/MarginContainer/VBoxContainer/ScrollContainer/PastText");
		vScrollBar = scroll.GetVScrollBar();
		vScrollBar.Changed += updateScroll;
		loadResource("res://resources/dialogues/dialogue_box_fallback.tres");
		hide();

		if (this == GetTree().CurrentScene)
		{
			invoke();
		}
	}

	public void hide()
	{
		this.Visible = false;
		foreach (Node child in oldTextContainer.GetChildren())
		{
			child.QueueFree();
			oldTextContainer.RemoveChild(child);
		}
	}

	public void invoke()
	{
		this.Visible = true;
		progress.Pressed += procede;
		current.Text = res.paragraphs[0];
		maxScrollValue = (int) vScrollBar.MaxValue;
	}

	public void invoke(string path)
	{
		loadResource(path);
		invoke();
	}

	public void loadResource(string path)
	{
		res = ResourceLoader.Load<TextBoxDialogue>(path);
	}

	private void updateScroll()
	{
		if (maxScrollValue == (int)vScrollBar.MaxValue)
			return;

		maxScrollValue = (int)vScrollBar.MaxValue;
		scroll.ScrollVertical = maxScrollValue;
	}

	private void procede()
	{
		if (i + 1 == res.paragraphs.Count)
		{
			return;
		}

		if (i + 2 == res.paragraphs.Count)
		{
			progress.Text = " /// Return /// ";
			progress.Pressed -= procede;
			progress.Pressed += hide;
		}

		current.Text = res.paragraphs[i + 1];
		RichTextLabel tmp = new RichTextLabel();
		oldTextContainer.AddChild(tmp);
		tmp.Name = "Paragraph" + i.ToString();
		tmp.FitContent = true;
		tmp.BbcodeEnabled = true;
		tmp.AddThemeColorOverride("default_color", new Color(1, 1, 1, 0.5f));
		tmp.Text = res.paragraphs[i];

		i++;
	}
}
