using System.Threading.Tasks;
using Godot;

namespace Cirno.Scripts.Components.Actors;

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

    protected Door _door;
    
    public override void _Ready()
    {
        
        _door = GetParent<Door>();
        
        _door.DoorOpened += DoorOpened;
        _door.DoorClosed += DoorClosed;
    }
    
    protected virtual void DoorOpened()
    {
        if (TurnOffMaterial is null) return;

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

    protected virtual void 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);
    }
}