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



namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class DilateTexture:Node
  {
    [ExportCategory("Readonly")]
    [Export]
    public SubViewport X_viewport;

    [Export]
    public TextureRect X_textureRect;

    public static readonly string dilateMaterialPath = "res://addons/rokojori_action_library/External/Imposter/materials/dilatate.material";

    public static Sampler2DPropertyName alphaTex = Sampler2DPropertyName.Create( "u_alpha_tex" );
    public static BoolPropertyName alphaOverwrite = BoolPropertyName.Create( "u_alpha_overwrite" );

    public async Task<Texture2D> Create( Texture2D texture2D, Texture2D alphaMask = null )
    {
      var overwriteAlpha = alphaMask != null;

      if ( ! overwriteAlpha )
      {
        alphaMask = texture2D;
      }

      this.DestroyChildren();

      X_viewport = this.CreateChild<SubViewport>( "Dilate Viewport" );
      X_viewport.World2D = new World2D();
      X_viewport.Size = (Vector2I) texture2D.GetSize();
      
      X_viewport.TransparentBg = true;
      X_viewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Always;

      X_textureRect = X_viewport.CreateChild<TextureRect>( "Texture" );
      X_textureRect.StretchMode = TextureRect.StretchModeEnum.Keep;
      X_textureRect.CustomMinimumSize = new Vector2( 4096, 4096 );

      X_textureRect.Texture = texture2D;

      var material = ResourceLoader.Load( dilateMaterialPath ) as ShaderMaterial;
      alphaTex.Set( material, alphaMask );
      alphaOverwrite.Set( material, overwriteAlpha );

      X_textureRect.Material = material;

      await this.RequestNextFrame();
      
      var viewportTexture = X_viewport.GetTexture();

      await this.RequestNextFrame(); 

      var image = viewportTexture.GetImage();

      return ImageTexture.CreateFromImage( image );
    }

  }
}