
using Godot;
using Rokojori;
using System.Collections.Generic;
using System.Linq;

namespace Rokojori
{ 
  [Tool]
  [GlobalClass,Icon("res://addons/rokojori_action_library/Icons/UISpace.svg")]
  public partial class UISpace:Control, UIHolderControl
  { 
    UI ui;

    int _uiAncestorDepth;

    public void ComputeUIAncestorDepth()
    {
      SetUIAncestorDepth( NodesWalker.Get().GetAncestorDistance( this, GetUI( false ) ) );
    }

    public void SetUIAncestorDepth( int depth )
    {
      _uiAncestorDepth = depth;
    }

    public int GetUIAncestorDepth()
    {
      return _uiAncestorDepth;
    }

    public override void _EnterTree()
    { 
      ComputeUIAncestorDepth();
    }

    public override void _ExitTree()
    {
      ui = null;
      _uiAncestorDepth = -1;
    }
    
    public void SetUI( UI ui,bool computeDepth = true )
    {
      this.ui = ui;

      if ( computeDepth )
      {
        ComputeUIAncestorDepth();
      }
    }

    public UI GetUI( bool computeDepth = true )
    {
      if ( this.ui != null )
      {
        return this.ui;
      }

      var ui = this.FindParentThatIs<UI>();

      if ( ui == null )
      {        
        _uiAncestorDepth = -1;
        // this.LogInfo( "No UI in parents >", HierarchyName.Of( this ) );

        return null;        
      }

      if ( computeDepth )
      { 
        ComputeUIAncestorDepth();
      }

      return ui;
    }

    public void Update()
    {      
      var ui = GetUI();

      if ( ! ui.fontSizeChanged )
      {
        return;
      }

      var currentFontSize = UIStyle.GetCurrentFontSize( this );
      Size = new Vector2( currentFontSize * 0.29f, 0 );

      // this.LogInfo( "Updating Space", currentFontSize );
    }

  }
}