using Godot;
using System;
using System.Collections.Generic;

public partial class ResourceGUIManager : CanvasLayer
{
	private float textlabel_offset = 20f;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		GameManager.Instance.ResModified += UpdateOverlay;
		GameManager.Instance.SimResModified += UpdateOverLaySimulation;
		CreateOverlay();
	}

	private void CreateOverlay()
	{
		int i = 0;
		foreach (var (res_name, res_value) in GameManager.Instance.Res)
		{
			CreateLabel(res_name, res_value, i * textlabel_offset);
			i++;
		}
	}

	private void UpdateOverlay(string res_name, int res_value)
	{
		Label to_update = GetNode<Label>(res_name + "_Label");
		if (to_update == null)
		{
			CreateLabel(res_name, res_value, GameManager.Instance.Res.Count);
		}
		else
		{
			to_update.Text = res_name + ": " + res_value;
		}
	}

	private void UpdateOverLaySimulation(string res_name, int sim_value)
	{
		string label_text = res_name + ": " + GameManager.Instance.GetRes(res_name) + " (" + sim_value + ")";
		Label to_simulate = GetNode<Label>(res_name + "_Label");
		if (to_simulate == null)
		{
			CreateLabel(res_name, label_text, GameManager.Instance.Res.Count);
		}
		else
		{
			to_simulate.Text = label_text;
		}
	}

	private void CreateLabel(string res_name, int res_value, float total_offset)
	{
		CreateLabel(res_name, res_name + ": " + res_value, total_offset);
	}
	
	private void CreateLabel(string res_name, string label_text, float total_offset)
	{
		Label label = new Label();
		label.Name = res_name + "_Label";
		label.Text = label_text;
		label.Position += new Vector2(0, total_offset);
		AddChild(label);
	}
}
