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



namespace Rokojori
{
  /** <summary for="class StandardMaterialOverride">
      
      <title>
        Resource to create foliage material overrides with standard material
      </title>
      
      <description>
        
      </description>

    </summary>  
  */

  [Tool]
  [GlobalClass, Icon("res://addons/rokojori_action_library/Icons/Scatterer.svg") ]
  public partial class StandardMaterialOverride:FoliageMaterialOverride
  {

    [Export]
    public FoliageTransparencyRenderMode transparencyRenderMode;

    [Export]
    public FoliageTextureOverride[] textureOverrides = [];

    public override void CreateFoliageOverideMaterial( FoliageRenderLayer foliageRenderLayer )
    { 
      var gpuParticles3D = foliageRenderLayer.gpuParticles3D;

      if ( gpuParticles3D.DrawPass1 == null )
      {
        return;
      }
      
      var originalMaterial = gpuParticles3D.DrawPass1.SurfaceGetMaterial( 0 );

      if ( ! ( originalMaterial is StandardMaterial3D || originalMaterial is OrmMaterial3D ) )
      {
        return;
      }

      var overrideMaterial = (StandardMaterial3D)originalMaterial.Duplicate();
      gpuParticles3D.MaterialOverride = overrideMaterial;

      UpdateFoliageOverideMaterial( foliageRenderLayer );
    }

    public override void UpdateFoliageOverideMaterial( FoliageRenderLayer foliageRenderLayer )
    {
      var material = foliageRenderLayer.gpuParticles3D.MaterialOverride;

      if ( material == null || ! ( material is StandardMaterial3D ) )
      {
        return;
      }

      var standardMaterial = (StandardMaterial3D) material;

      transparencyRenderMode?.ApplyTransparencyMode( standardMaterial, foliageRenderLayer );

      textureOverrides.ForEach(
        ( to )=>
        {
          if ( to == null )
          {
            return;
          }

          to.Apply( material );
        }
      );
    }

    public override Material GetOverrideMaterial(FoliageRenderLayer foliageRenderLayer)
    {      
      var material = foliageRenderLayer.gpuParticles3D.MaterialOverride;
      return material;
    }
  }
}