using System.Collections;
using System.Collections.Generic;
using Godot;
using System;
using System.Threading;
using System.Threading.Tasks;


namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class TextureCombinerTextureLayer:TextureCombinerLayer
  {
    [Export]
    public Texture2D texture;

    [Export]
    public Vector2 tiling = Vector2.One;

    [Export]
    public Vector2 offset = Vector2.Zero;

    [Export]
    public bool updateTexture = true;

    TextureCombinerBuffer textureBuffer;

    public override async Task Process( TextureCombinerProcessingRect processingRect )
    {
      var time = Async.StartTimer();

      if ( updateTexture || textureBuffer == null )
      {
        textureBuffer = TextureCombinerBuffer.From( texture );

        time = await Async.WaitIfExceeded( time );
      }


      for ( int i = 0; i < processingRect.processingWidth; i++ )
      {
        for ( int j = 0; j < processingRect.processingHeight; j++ )
        {
          var uv    = processingRect.GetRelativeUV( i, j );

          uv *= tiling;
          uv += offset;

          uv = uv.PosMod( 1f );
          
          var color = textureBuffer.SampleBilinearUV( uv );

          processingRect.SetOutputRelative( i, j, color );
        }
      }

      return;
    }
  }
}