using Godot;
using System.Collections;
using System.Collections.Generic;
using Godot.Collections;

namespace Rokojori
{
  [GlobalClass,Tool]
  public partial class TimeInfo:Node
  { 
    [Export]
    public Node3D parent;

    [Export]
    public Font font;

    [Export]
    public float fontInnerSize = 32;

    [Export]
    public float fontOutlineSize = 12;

    [Export]
    public float fontPropertiesScale = 2f;


    [Export]
    public int maxMessages;
    
    [Export]
    public Duration showDuration;

    [Export]
    public Node3D positionSource;

    [Export]
    public Vector3 positionOffset = new Vector3( 0, 1, 0 );

    [Export]
    public Curve curve;

    [Export]
    public float curveMultiplier = 1f;

    [Export]
    public float increaseDuration = 0.5f;

    [Export]
    public float increaseOffset = 0.5f;

    [Export]
    public float hueSpeed = 360;

    [Export]
    public float saturation = 1;

    [Export]
    public float luminance = 0.7f;

    int id = 0;

    float _last = 0;
    int _currentOffset = 0;

    public void Show( string info, float scale )
    {
      id++;

      var now = TimeLine.osTime;
      var elapsed = now - _last;

      if ( elapsed < increaseDuration )
      {
        _currentOffset ++;
      }
      else
      {
        _currentOffset = 0;
      }

      _last = now;
      var text = parent.CreateChild<Label3D>( "Message-" + id );
      text.Font = font;
      text.FontSize = (int)( fontInnerSize * fontPropertiesScale * scale );
      text.OutlineSize = (int)( fontOutlineSize * fontPropertiesScale * scale);
      text.Billboard = BaseMaterial3D.BillboardModeEnum.Enabled;
      text.Text = info;

      var startPosition = positionSource.GlobalPosition + positionOffset + Vector3.Up * ( increaseOffset * _currentOffset );
      text.GlobalPosition = startPosition;

      TimeLineManager.ScheduleSpanWith( showDuration, 
        ( s, t )=>
        { 
          var hue = s.phase * hueSpeed;
          var color = new HSLColor( hue, saturation, luminance );
          color.a = 1f -  s.phase;
          text.Modulate = color;
          text.OutlineModulate = new Color( 0, 0, 0, color.a );
          var offset = curve.Sample( s.phase ) * curveMultiplier;
          var position = startPosition + offset * Vector3.Up;

          text.GlobalPosition = position;
          if ( TimeLineSpanUpdateType.End == t )
          {
            text.SelfDestroy(); 
          }
          
        } 
      );
    } 
  }
}