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

public partial class ResourceUIHandler : VBoxContainer
{
        [Export(PropertyHint.File, "*.tscn")] public string bar_path;
        [Export(PropertyHint.File, "*.tscn")] public string item_path;

        private PackedScene bar_template;
        private PackedScene item_template;
        private Control container;
        private Dictionary<string, ResourceUIElement> rows;

        public override void _Ready()
        {
                rows = new Dictionary<string, ResourceUIElement>();
                bar_template = GD.Load<PackedScene>(bar_path);
                item_template = GD.Load<PackedScene>(item_path);
                container = GetNode<Control>("HBoxContainer");
                GameManager.Instance.NewResModified += _UpdateRes;
                GameManager.Instance.NewResAdded += _UpdateRes;
                GameManager.Instance.InvalidQueue += _Alert;

                foreach ((string s, GameResource res) in GameManager.Instance.newRes)
                {
                        _Instantiate(res);
                }
        }

        public override void _ExitTree()
        {
                GameManager.Instance.NewResModified -= _UpdateRes;
                GameManager.Instance.NewResAdded -= _UpdateRes;
                GameManager.Instance.InvalidQueue -= _Alert;
        }

        private void _Instantiate(GameResource res)
        {
                ResourceUIElement tmp;
                if (res.max == -1)
                {
                        tmp = item_template.Instantiate<ResourceItem>();
                }
                else
                {
                        tmp = bar_template.Instantiate<ResourceBar>();
                }
                container.AddChild(tmp);
                tmp.set_data(res.title, new PlaceholderTexture2D());
                tmp.set_color(res.critical);
                tmp.set_values(res.value, res.proxy, res.max);
                rows.Add(res.identifier, tmp);
        }

        private void _UpdateRes(GameResource res)
        {
                GD.Print("Called UpdateRes UI for [" + res.identifier + "]");
                if (rows.ContainsKey(res.identifier))
                {
                        GD.Print("Not instantiating");
                        ResourceUIElement element = rows[res.identifier];
                        element.set_values(res.value, res.proxy, res.max);
                }
                else
                {
                        _Instantiate(res);
                }
        }

        private void _Alert(string id)
        {
                if (rows.ContainsKey(id))
                {
                        rows[id].alert();
                }
        }

}
