using System.Threading.Tasks;
using Godot;

namespace Cirno.Scripts.Components.Actors;

public partial class ForceFieldSpriteComponent : DoorSpriteComponent
{
    [Export]
    public Material TurnOffMaterial { get; private set; }
    
    [Export]
    public Material ActiveMaterial { get; private set; }

    protected override void DoorOpened()
    {
        base.DoorOpened();
        if (TurnOffMaterial is null) return;

        this.Material = TurnOffMaterial;
        _ = AnimateShutdownAsync();
    }

    protected override void DoorClosed()
    {
        base.DoorClosed();
        if (ActiveMaterial is null) return;
        this.Material = ActiveMaterial;
    }
    
    protected async Task AnimateShutdownAsync() 
    {
        Tween tween = GetTree().CreateTween();
        tween.TweenMethod(Callable.From((float value) => SetShaderScanlineDensity(value)), 0f, 50f, 0.5);
        tween.Parallel().TweenMethod(Callable.From((float value) => SetShaderTeleportProgress(value)), 0f, 1f, 0.5);

        await ToSignal(tween, "finished");
    }
    
    private void SetShaderTeleportProgress(float value)
    {
        ((ShaderMaterial)this.Material).SetShaderParameter("teleport_progress", value);
    }

    private void SetShaderScanlineDensity(float value)
    {
        ((ShaderMaterial)this.Material).SetShaderParameter("scanline_density", value);
    }
}