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

namespace Rokojori
{
  [GlobalClass,Tool]
  public partial class EatDaRichGame:Node
  {
    public enum State
    {
      Title,
      Intro,
      Playing,
      Outro
    }

    [Export]
    public State state = State.Title;

    [Export]
    public EatDaRichStats gameStats;


    [Export]
    public float secondsLeft = 120;

    [Export]
    public float secondsPlaying = 0;


    [Export]
    public int numRich = 0;

    [Export]
    public GameTimer gameTimer;

    [Export]
    public CountNumber countRichInOutro;

    public void ChangeTime( float delta )
    {
      secondsLeft += delta;
    }
    

    public override void _Process( double delta )
    {
      if ( State.Playing == state )
      {
        OnPlaying( (float) delta );
      }



    }

    void OnPlaying( float delta )
    { 
      secondsLeft -= (float) delta;
      secondsPlaying += (float) delta;

      var timerSeconds = Mathf.Max( secondsLeft, 0 ); 
      gameTimer.timer.locale = LocaleText.Create( Duration.GetTimerLabel( timerSeconds ) );

      if ( secondsLeft <= 0 )
      {
        SetState( State.Outro );
      }
    }

    public void SetState( State state )
    {
      this.LogInfo( "Set State:", state );

      if ( State.Playing == state )
      {
        secondsLeft = gameStats.secondsToPlay;
        numRich = 0;
        secondsPlaying = 0;
      }

      if ( State.Outro == state )
      {
        countRichInOutro.startValue = 0;
        countRichInOutro.endValue = numRich;

        Action.Trigger( countRichInOutro );
      }

      SetNextState( state );

    }

    async void SetNextState( State state )
    {
      await this.RequestNextFrame();

      this.state = state;

      this.ForEachInRoot<OnState>(
        ( sta )=>
        {
          if ( sta.state == state )
          {
            Action.Trigger( sta.action );
          }
        }
      );

    }

  }
}