using Godot;
using System;

public partial class Cue : Sprite2D
{
	[Signal]
	public delegate void ShootEventHandler(Vector2 IMPULSE);
	
	public bool _donned = false, _equiped = false, _sending = false;
	public float _power = 0.0f, _maxPower = 20.0f;
	Vector2 _direction;
	public ProgressBar _progressBar;
	
	public static Cue Create(string SCENENAME)
	{
		PackedScene scene = ResourceLoader.Load<PackedScene>("res://Gameplay/"+SCENENAME+".tscn");
		Cue newCue = scene.Instantiate<Cue>();
		Texture2D image = GD.Load<Texture2D>("res://art/cue.png");
		newCue.Texture = image;
		return newCue;
	}
	
	public override void _Ready()
	{
		//_progressBar = GetParent().GetNode<ProgressBar>("PowerBar");
	}

	public override void _Process(double DELTA_)
	{
		
		if (!_sending)
		{
			Vector2 mousePosition = GetViewport().GetMousePosition();
			Offset = new Vector2(_power * -10, 0);
			LookAt(mousePosition);
			if (Input.IsActionJustPressed("scroll_down"))
			{
				_power = Math.Min(_power + (1f * (Input.IsActionPressed("shift") ? 5 : 1) / (Input.IsActionPressed("ctrl") ? 10 : 1)), _maxPower);
			}
			else if (Input.IsActionJustPressed("scroll_up"))
			{
				_power = Math.Max(_power - (1f * (Input.IsActionPressed("shift") ? 5 : 1) / (Input.IsActionPressed("ctrl") ? 10 : 1)), 0);
			}

			if (Input.IsActionJustReleased("left_click"))
			{
				if (_power > 0f)
				{
					_sending = true;
					_direction = mousePosition - Position;
				}
			}
		}
		else
		{
			if (Offset.X < 0)
			{
				Offset = new Vector2(Math.Min(0, Offset.X + _power * 2), 0);
			}
			else
			{
				_sending = false;
				Offset = Vector2.Zero;
				EmitSignal(SignalName.Shoot, _power * _direction);
				_power = 0;
			}
		}
		
		
	}
	
	public void Doff()
	{
		_donned = false;
		SetProcess(false);
		Hide();
		//_progressBar.Hide();
	}

	public void Don(Ball CUEBALL)
	{
		_donned = true;
		Position = CUEBALL.Position;
		SetProcess(true);
		Show();
		//_progressBar.Position = new Vector2(CUEBALL.Position.X - _progressBar.Size.X / 2, CUEBALL.Position.Y + _progressBar.Size.Y / 2);
		//_progressBar.Show();
	}
	
}
