using Godot;
 
namespace Rokojori
{ 

  [Tool]
  [GlobalClass,Icon("res://addons/rokojori_action_library/Icons/UI.svg")]
  public partial class UI : Control
  { 
    [Export]
    public UISettings settings;

    [Export]
    public InputIconsLibrary inputIconsLibrary;

    [ExportGroup("Font Settings")]

    [Export]
    public UINumber fontSize;

    [Export]
    public Font defaultFont;

    [Export]
    public float fontZoom = 1;

    [ExportGroup("Update Mode")]
    [Export]
    public bool updateFlag = false;

    [Export]
    public bool updateAlways = true;

    [ExportGroup("Read Only")]

    [Export]
    public float X_computedFontSizePixels = 1;    

    public override void _Process( double delta )
    {      
      UpdateFontSize();
      UpdateUIElements();
    }

    public override void _Ready()
    {
      var sm = Unique<SensorManager>.Get();
      
      if ( sm != null )
      {
        sm._onActiveDeviceChange.AddAction( a => UpdateUIInputs() );
      }

      UpdateUIInputs();
    } 

    void UpdateUIInputs()
    { 
      Nodes.ForEach<UIInputInfo>( this, uii => uii.updateInfo = true );
    }



    void UpdateFontSize()
    {
      X_computedFontSizePixels = UINumber.Compute( this, fontSize ) * fontZoom;   

      if ( Theme != null )
      {
        Theme.DefaultFontSize = Mathf.RoundToInt( X_computedFontSizePixels );
      }
    }

    void UpdateUIElements()
    {
      if ( ! ( updateFlag || updateAlways ) )
      {
        return;
      }

      updateFlag = false;

      Nodes.ForEachDirectChild<UIRegion>( this, r => r.Layout() );
    }


    public static float GetWindowWidth( Control control )
    {
      if ( Engine.IsEditorHint() )
      {
        return ProjectSettings.GetSetting( "display/window/size/viewport_width" ).AsInt32();
      }
      else
      {
        return control.GetWindow().Size.X;
      }
    }

    public static float GetWindowHeight( Control control )
    {
      if ( Engine.IsEditorHint() )
      {
        return ProjectSettings.GetSetting( "display/window/size/viewport_height" ).AsInt32();
      }
      else
      {
        return control.GetWindow().Size.Y;
      }
    }
    

  }
}