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

public partial class Actor : Node
{
	public bool _available, _hovered, _selected;
	public List<Cue> _cues = new();
	public Cue _activeCue;
	public List<Ball> _balls = new();
	public Ball _activeBall;
	
	public static Actor Create(string SCENENAME)
	{
		PackedScene scene = ResourceLoader.Load<PackedScene>("res://Gameplay/"+SCENENAME+".tscn");
		Actor newActor = scene.Instantiate<Actor>();
		return newActor;
	}
	
	public override void _Ready()
	{
		Ball newBall = Ball.Create("ball", 0);
		AddChild(newBall);
		_balls.Add(newBall);
		if (_activeBall == null)
		{
			_activeBall = _balls[0];
		}
		Cue newCue = Cue.Create("cue");
		AddChild(newCue);
		_cues.Add(newCue);
		if (_activeCue == null)
		{
			_activeCue = _cues[0];
			_activeCue.Shoot += OnCueShoot;
		}
	}
	
	public override void _Process(double DELTA_)
	{
		if (!_activeBall._placed)
		{
			Vector2 mousePosition = GetViewport().GetMousePosition();
			_activeBall.Position = mousePosition;
			if (Input.IsActionJustReleased("left_click"))
			{
				_activeBall.Place(mousePosition);
			}
		}
		else
		{
			_hovered = _activeBall._hovered;
			if (_activeCue._shown)
			{
				if (!_activeBall._available)
				{
					_activeCue.HideCue();
				}
			}
			else // (!_activeCue._shown)
			{
				if (_activeBall._available)
				{
					_activeCue.ShowCue(_activeBall);
				}
			}
		}
		
		
	}
	
	
	//public void ResetCueBall()
	//{
		//_cueBall = Ball.Create("ball", 0, _startPosition);
		//_cueBall.SetName("CueBall");
		//AddChild(_cueBall);
		//Texture2D image = GD.Load<Texture2D>("res://art/cue_ball.png");
		//_cueBall.GetNode<Sprite2D>("Image").Texture = image;
		//_cueBall._placed = true;
		//_balls = GetTree().GetNodesInGroup("balls").Select(b => (Ball)b).ToList<Ball>();
	//}
	
	private void OnCueShoot(Vector2 IMPULSE)
	{
		_activeBall.ApplyCentralImpulse(IMPULSE);
	}
}
