using Godot;
using System;

public partial class Startup : Node2D
{
	private enum State
	{
		Default,
		TransitionIn,
		TransitionOut
	}

	private State _state = State.Default;

	private ColorRect _colorRect;

	private AudioStreamPlayer _music;

	private double _transitionTimeout = 0;
	
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		_colorRect = (ColorRect)FindChild("ColorRect");
		_music = (AudioStreamPlayer)FindChild("AudioStreamPlayer");
		_state = State.TransitionIn;
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _PhysicsProcess(double delta)
	{
		if (_state == State.TransitionOut)
		{
			_transitionTimeout += delta;
			// _colorRect.Color = _colorRect.Color.Lerp(new Color(0, 0, 0, 255), (float)_transitionTimeout/2);
			_colorRect.Color = new Color(0, 0, 0, Mathf.Lerp(0, 1, (float)_transitionTimeout/2));
			_music.VolumeDb = Mathf.Lerp(0, -41, (float)_transitionTimeout/2);
			if (_music.VolumeDb < -40)
			{
				GetNode<SceneManager>("/root/SceneManager").SwitchScene("Day1");
			}
		}
		if (_state == State.TransitionIn)
		{
			if (_transitionTimeout < 2)
			{
				_transitionTimeout += delta;
				// _colorRect.Color = _colorRect.Color.Lerp(new Color(0, 0, 0, 255), (float)_transitionTimeout/2);
				_colorRect.Color = new Color(0, 0, 0, Mathf.Lerp(1, 0, (float)_transitionTimeout/2));
				_music.VolumeDb = Mathf.Lerp(-40, 0, (float)_transitionTimeout/2);
			}
			else
			{
				_state = State.Default;
				_transitionTimeout = 0;
			}
		}
	}

	public override void _Input(InputEvent @event)
	{
		if (@event.IsActionPressed("Interact"))
		{
			_state = State.TransitionOut;
		}
		if (@event.IsActionPressed("ui_cancel"))
		{
			GetTree().Quit();
		}
	}
}
