#if TOOLS
using Godot;

public partial class FloatModsProperty : EditorProperty
{
	private VBoxContainer _modsControl;
	private FloatModifiers _currentValue;
	private bool _updating;

	public FloatModsProperty()
	{
		_modsControl = GD.Load<PackedScene>("res://addons/floatmodifiers/float_mods_property.tscn").Instantiate<VBoxContainer>();
		AddChild(_modsControl);
		AddFocusable(_modsControl);

		RefreshControl();

		_modsControl.GetNode<SpinBox>("%Flat").ValueChanged += UpdateFlat;
		_modsControl.GetNode<SpinBox>("%Percentage").ValueChanged += UpdatePercentage;
		_modsControl.GetNode<SpinBox>("%Mult").ValueChanged += UpdateMult;
	}

	private void UpdateFlat(double value)
	{
		if (_updating) return;

		_currentValue.SetFlat((float)value);

		RefreshControl();
		EmitChanged(GetEditedProperty(), _currentValue);
	}
	private void UpdatePercentage(double value)
	{
		if (_updating) return;

		_currentValue.SetPercentage((float)value);

		RefreshControl();
		EmitChanged(GetEditedProperty(), _currentValue);
	}
	private void UpdateMult(double value)
	{
		if (_updating) return;

		_currentValue.SetMult((float)value);

		RefreshControl();
		EmitChanged(GetEditedProperty(), _currentValue);
	}

	private void RefreshControl()
	{
		if (_currentValue == null)
		{
			return;
		}

		_modsControl.GetNode<SpinBox>("%Flat").SetValueNoSignal(_currentValue.GetFlat());
		_modsControl.GetNode<SpinBox>("%Percentage").SetValueNoSignal(_currentValue.GetPercentage());
		_modsControl.GetNode<SpinBox>("%Mult").SetValueNoSignal(_currentValue.GetMult());
	}


	public override void _UpdateProperty()
	{
		// Read the current value from the property.
		var newValue = GetEditedObject().Get(GetEditedProperty()).As<FloatModifiers>();
		if (newValue == null)
		{
			newValue = new();
			newValue.ResourceLocalToScene = true;
			EmitChanged(GetEditedProperty(), newValue);
		}
		if (newValue.ResourceLocalToScene == false)
		{
			newValue.ResourceLocalToScene = true;
		}
		if (newValue == _currentValue)
			{
				return;
			}

		// Update the control with the new value.
		_updating = true;
		_currentValue = newValue;
		RefreshControl();
		_updating = false;
	}
}
#endif