using UnityEngine;
using UnityEngine.InputSystem;

public class Bunker : MonoBehaviour
{
	[SerializeField] private TrajectoryCommand _trajectoryCommand = null;

	[SerializeField] private BunkerStationLaunch _launchStation = null;

	[SerializeField] private BunkerStationCurve _curveStationA = null;
	[SerializeField] private BunkerStationCurve _curveStationB = null;
	[SerializeField] private BunkerStationCurve _curveStationC = null;

	[SerializeField] private Launcher _rocketLauncher = null;

	[SerializeField] private RootDrawer _rootDrawer = null;

	private void Start()
	{
		_launchStation.LaunchButtonPressedEvent += OnLaunchStationPressed;

		_curveStationA.InteractEvent += OnCurveStationAPressed;
		_curveStationB.InteractEvent += OnCurveStationBPressed;
		_curveStationC.InteractEvent += OnCurveStationCPressed;

		ReloadRocket();
	}

	// public void Update()
	// {
		// // Translation Rotation Fire
		// if (Keyboard.current.spaceKey.wasPressedThisFrame)
		// {
		// 	_launchStation.Press();
		// }
		//
		// // Curves
		// if (Keyboard.current.aKey.wasPressedThisFrame)
		// {
		// 	_curveStationA.Press();
		// }
		//
		// if (Keyboard.current.sKey.wasPressedThisFrame)
		// {
		// 	_curveStationB.Press();
		// }
		//
		// if (Keyboard.current.dKey.wasPressedThisFrame)
		// {
		// 	_curveStationC.Press();
		// }
	// }

	public void StopLauncherTranslation()
	{
        _rocketLauncher.StartRotation();
	}

	public void StopLauncherRotation()
	{
		_rocketLauncher.StopRotation();
	}

	public void FireRocket()
	{
		// Fire
		Debug.Log("Fire");

		_rocketLauncher.LaunchRocket(_trajectoryCommand.TrajectoryGenerator.CurrentTrajectory, 1f);
		_rootDrawer.StartRoot(_rocketLauncher.CurrentRocket);

		// Reload
		ReloadRocket();
	}

	public void ReloadRocket()
	{
		Debug.Log("Reload");

		// Generate Random Curves
		_curveStationA.SetSinusoid(TrajectoryBank.GetRandomCurve());
		_curveStationB.SetSinusoid(TrajectoryBank.GetRandomCurve());
		_curveStationC.SetSinusoid(TrajectoryBank.GetRandomCurve());

		_trajectoryCommand.SetSinusoids(
			_curveStationA.Sinusoid,
			_curveStationB.Sinusoid,
			_curveStationC.Sinusoid
		);

		_trajectoryCommand.ResetTrajectory();

		// Reload Launcher
		_rocketLauncher.Reset();
		_rocketLauncher.CreateRocket();
	}

	private void OnLaunchStationPressed(StationLaunchMode launchMode)
	{
		Debug.Log("Launch mode is: " + launchMode);
		switch (launchMode)
		{
			case StationLaunchMode.POSITION:
				StopLauncherTranslation();
				StopLauncherRotation();
				break;
			case StationLaunchMode.ROTATION:
				break;
			case StationLaunchMode.LAUNCH:
				if (_trajectoryCommand.NbCurves > 0)
				{
					FireRocket();
				}
				break;
		}
	}

	private void OnCurveStationAPressed()
	{
		_trajectoryCommand.AddA();
	}

	private void OnCurveStationBPressed()
	{
		_trajectoryCommand.AddB();
	}

	private void OnCurveStationCPressed()
	{
		_trajectoryCommand.AddC();
	}
}
