using Godot;
using System;

public partial class Day : Node2D
{
	[Export] public string NextScene;
	[Export] public bool IsEngineDisabled = true;
	[Export] public bool IsCaptainDisabled = false;
	private enum State
	{
		Default,
		TransitionIn,
		TransitionOut
	}

	private State _state = State.TransitionIn;

	private Player _player;
	private ColorRect _colorRect;
	private AudioStreamPlayer _music;
	private AudioStreamPlayer _nightmare;
	private Interactable _endDay;
	private NPC _engine;
	private Door _captainDoor;
	
	private double _transitionTimeout = 0;

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		_player = (Player)FindChild("Player");
		_colorRect = _player.CRect;
		_music = (AudioStreamPlayer)FindChild("Music");
		_nightmare = (AudioStreamPlayer)FindChild("Nightmare");
		_endDay = (Interactable)FindChild("EndDay");
		_engine = (NPC)FindChild("Engine");
		_captainDoor = (Door)FindChild("Door_CAPTAIN");
		_colorRect.Color = new Color(0, 0, 0, 1f);
		_music.VolumeDb = -40;
		_player.CurrentState = Player.State.Wait;
		_endDay.Disable();
		if (IsEngineDisabled) _engine.Disable();
		if (IsCaptainDisabled) _captainDoor.Disable();
	}

	public void EnableEngine()
	{
		_engine.Enable();
	}

	public void EnableCaptain()
	{
		_captainDoor.Enable();
	}
	
	public void AssignEndDay(Player player)
	{
		player.InteractableObjects.Add(_endDay);
	}
	public void RemoveEndDay(Player player)
	{
		player.InteractableObjects.Remove(_endDay);
	}
	
	public void ChangeDay()
	{
		_state = State.TransitionOut;
	}

	public void EnableEndDay()
	{
		_endDay.Enable();
	}

	public void ChangeScene()
	{
		GetNode<SceneManager>("/root/SceneManager").SwitchScene(NextScene);
	}
	
	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		if (_state == State.TransitionIn)
		{
			if (_transitionTimeout <= 1)
			{
				_transitionTimeout += delta;
				_music.VolumeDb = Mathf.Lerp(-40, 0, (float)_transitionTimeout);
				_colorRect.Color = new Color(0, 0, 0, Mathf.Lerp(1, 0, (float)_transitionTimeout));
			}
			else
			{
				_state = State.Default;
				_player.CurrentState = Player.State.Normal;
				_transitionTimeout = 0;
			}
		}
		if (_state == State.TransitionOut)
		{
			_player.CurrentState = Player.State.Wait;
			if (_transitionTimeout <= 1)
			{
				_transitionTimeout += delta;
				_music.VolumeDb = Mathf.Lerp(0, -40, (float)_transitionTimeout);
				_colorRect.Color = new Color(0, 0, 0, Mathf.Lerp(0, 1, (float)_transitionTimeout));
			}
			else
			{
				_state = State.Default;
				_music.Stop();
				_nightmare.Play();
			}
		}
	}
}
