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

namespace Rokojori
{
  [GlobalClass,Tool]
  public partial class Eat:Action
  {
    [Export]
    public OnCollision onCollision;

    [Export]
    public Action onAteSomething;

    [Export]
    public Pointer pointer;

    [Export]
    public Jump jump;

    float _lastPig = 0;

    protected override void _OnTrigger()
    {
      var pigs = onCollision.GetNodesInside();  

      var hasEaten = false;

      var edr = Unique<EatDaRichGame>.Get();

      var now = TimeLine.osTime;

      var elapsed = now - _lastPig;

      var fastMultiply = 1f;
      var isFast = false;
      var isAir = jump.IsJumping();
      var isLongAir = jump.GetAirTime() > edr.gameStats.longAirDuration;


      if ( elapsed < edr.gameStats.fastDurationInSeconds )
      {
        isFast = true;
        fastMultiply = edr.gameStats.fastMultiply;
      }

      var ti = Unique<TimeInfo>.Get();


      pigs.ForEach(
        ( p )=>
        {
          var eatable = p.Get<Eatable>();

          this.LogInfo( eatable );

          if ( eatable == null || ! eatable.isEatable ) 
          {            
            return;
          }

          eatable.GetEaten();

          var value = edr.gameStats.basicPigSeconds;
          var info = "PIG";

          if ( isAir )
          {
            value = edr.gameStats.pigInAirSeconds;

            if ( isLongAir )
            {
              value *= edr.gameStats.longAirMultiply;
            }

            info = isLongAir ? "PIG + LONG-AIR-TIME" : "PIG + AIR";
          }

          if ( isFast )
          {
            info = "( " + info + ") * SUPER-FAST "; 
          }

          if ( pigs.Count > 1 )
          {
            if ( !  isFast )
            {
              info = "( " + info + " )";
            }

            info += " x MULTI x " + pigs.Count; 
          }

          var combinedValue = ( value * fastMultiply ) * pigs.Count;

          edr.ChangeTime( combinedValue );

          hasEaten = true;
          
          ti.Show( info, 1 );
          ti.Show( "+" + combinedValue._F() + "sec ", 2 );
          
          
        }

      );

      if ( hasEaten )
      {
        _lastPig = now;
        Trigger( onAteSomething );
      }

      this.LogInfo( pigs );
    }
  }
}