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

namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class TextureChannelMixer:Action
  { 
    [Export]
    public string inputTexturePath;

    [Export]  
    public string outputTexturePath;

    [Export]
    public ImageSaveSettings outputFormat;

    [Export]
    public TextureChannelMixerPreset preset;

    [ExportGroup("Channel Adjustments")]
    [Export]
    public float redMultiply = 1;

    [Export]
    public float redOffset = 0;

    [Export]
    public float greenMultiply = 1;

    [Export]
    public float greenOffset = 0;

    [Export]
    public float blueMultiply = 1;

    [Export]
    public float blueOffset = 0;

    [Export]
    public float alphaMultiply = 1;

    [Export]
    public float alphaOffset = 0;


    protected override void _OnTrigger()
    {
      if ( preset == null || 
           preset.red == null ||
           preset.green == null ||
           preset.blue == null ||
           preset.alpha == null 
      )
      { 
        this.LogError( "The preset is not correctly setup for each channel. Add a preset and for each channel add a setting" );
        return;
      }

      var texture = ResourceLoader.Load<Texture2D>( inputTexturePath );
      var sourceBuffer = TextureCombinerBuffer.From( texture );
      var outputBuffer = TextureCombinerBuffer.Create( sourceBuffer.width, sourceBuffer.height );

      this.LogInfo( "Processing:", inputTexturePath, ">>", sourceBuffer.numPixels + " pixels" );

      for ( int i = 0; i < sourceBuffer.numPixels; i++ )
      {
        var sourceColor = sourceBuffer.GetIndexed( i );
        var outputColor = new Color(
          preset.red.GetValue( sourceColor ) * redMultiply + redOffset,
          preset.green.GetValue( sourceColor ) * greenMultiply + greenOffset,
          preset.blue.GetValue( sourceColor ) * blueMultiply + blueOffset,
          preset.alpha.GetValue( sourceColor ) * alphaMultiply + redOffset
        );

        outputBuffer.SetIndexed( i, outputColor );
      }

      this.LogInfo( "Saving:", outputTexturePath );

      var it = outputBuffer.CreateImageTexture( preset.alpha.isAssigned, false );

      var image = it.GetImage();
      outputFormat.Save( image, outputTexturePath );
    
    }

  }
}