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

namespace Rokojori
{  
  
  [Tool]
  [GlobalClass,Icon("res://addons/rokojori_action_library/Icons/App.svg")]
  public partial class AppPreset: Node
  { 
    [Export]
    public MainModule mainModule;

    [Export]
    public FeatureModule[] features = [];

    
    public enum RenderQualitySettingsMode
    {
      Keep,
      High,
      Low     
    }

    [Export]
    public RenderQualitySettingsMode renderQualitySettings = RenderQualitySettingsMode.High;

    public enum RootMode
    {
      Create_Root,
      Use_Existing_Root
    }

    [ExportToolButton( "Create" )] 
    public Callable createButton => Callable.From(
      ()=>
      {
        Create();
      }
    );

    [ExportGroup("Options")]

    [Export]
    public RootMode rootMode;
    [Export]
    public App existingRoot;

    [Export]
    public bool removeSelf = false;

    public enum PresetErrorHandlingMode
    {
      Automatic_Fix,
      Ignore      
    }

    [Export]
    public PresetErrorHandlingMode errorHandling;
    
    

    async Task Create()
    {
      var root = existingRoot;
      
      if ( RootMode.Create_Root == rootMode )
      {
        var parent = GetParent();
        root = parent.CreateChild<App>( "App" );
      }

      var context = new PresetContext();
      context.root = root;
      context.appPreset = this;

      var passes = new List<PresetPass>{ 
        PresetPass.Prefly,
        PresetPass.Prepare, 
        PresetPass.Process, 
        PresetPass.Post 
      };

      foreach ( var p in passes )
      {
        context.pass = p;
        
        if ( mainModule != null )
        {
          await mainModule.ProcessPass( context );
        }

        if ( features == null )
        {
          continue;
        }

        foreach ( var f in features )
        {
          if ( f != null )
          {
            await f.ProcessPass( context );
          }
        }        
      }

      if ( RenderQualitySettingsMode.Keep != renderQualitySettings )
      {
        RenderQualitySettings.SetQuick( RenderQualitySettingsMode.High == renderQualitySettings );
      }

      if ( removeSelf )
      {
        this.SelfDestroy();
      }

      return;

    }

  }
}