using Godot;
using System;

public partial class CodingWindow : PanelContainer
{
	public PackedScene movePrefab;
	public PackedScene craftPrefab;
	public PackedScene harvestPrefab;
	
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		movePrefab = ResourceLoader.LoadMoveNodePrefab();
		craftPrefab = ResourceLoader.LoadCraftNodePrefab();
		harvestPrefab = ResourceLoader.LoadHarvestNodePrefab();
		GenerateCodingBlocks();
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		if (Input.IsActionJustPressed("codingwindow"))
		{
			Visible = !Visible;
			GameData.canMove = !Visible;
			if (Visible)
			{
				ReloadRobots();
			}
		} 
	}

	//Move, Harvest, Craft
	public void GenerateCodingBlocks()
	{
		VBoxContainer codingBlocks = GetNode<VBoxContainer>("./HBoxContainer/CodeBlocks/VBoxContainer");

		NodeDisplay node = new NodeDisplay();
		MoveNode move = new MoveNode();
		move.editorDisplay = movePrefab;
		node.SetNode(move);
		node.SetupUIElement();
		codingBlocks.AddChild(node);

		
		node = new NodeDisplay();
		CraftNode craft = new CraftNode();
		craft.editorDisplay = craftPrefab;
		node.SetNode(craft);
		node.SetupUIElement();
		codingBlocks.AddChild(node);

		node = new NodeDisplay();
		HarvestNode harvest = new HarvestNode();
		harvest.editorDisplay = harvestPrefab;
		node.SetNode(harvest);
		node.SetupUIElement();
		codingBlocks.AddChild(node);
	}

	public void ReloadRobots()
	{
		VBoxContainer robotList = GetNode<VBoxContainer>("./HBoxContainer/Robotlist/VBoxContainer");
		foreach(Node node in robotList.GetChildren())
		{
			robotList.RemoveChild(node);
			node.QueueFree();
		}
		PackedScene nodePrefab = ResourceLoader.LoadProgramNodePrefab();
		Control robot;

		foreach (Robot robotObject in GameData.robots)
		{
			robot = nodePrefab.Instantiate<Control>();
			robot.GetNode<RichTextLabel>("./Node/NodeContainer/NodeText").Text = robotObject.Name;
			GetNode<VBoxContainer>("./HBoxContainer/Robotlist/VBoxContainer").AddChild(robot);
		}
	}

	public void ClearWindow()
	{
		VBoxContainer nodeList = GetNode<VBoxContainer>("./HBoxContainer/EditorWindow/CodeContainer/VBoxContainer");
		foreach(Node node in nodeList.GetChildren())
		{
			nodeList.RemoveChild(node);
			node.QueueFree();
		}
	}

	public void CompileProgram()
	{
		
	}
}
