using Cirno.Scripts.Components.FSM;
using Godot;

namespace Cirno.Scripts.Components.Actors;

public partial class ConveyorBeltMover : PlayerArea2DModule
{
    public bool Enabled { get; private set; } = false;
    
    private Vector2 _velocity = Vector2.Zero;

    private IStateMachine<PlayerState, CharacterBody2D> _machine;
    
    public override void Init(IStateMachine<PlayerState, CharacterBody2D> machine)
    {
        base.Init(machine);
        
        _machine = machine;
    }
    
    private void OnBodyEntered(Node2D body)
    {
        if (!Enabled) return;
        if (body is not TileMapLayer tileMap) return;
        GD.Print($"Entered {body.Name}");
        
        // How do I get the actual coords of the cell at the collision point??
        var localTilemapCoords = tileMap.ToLocal(this.GlobalPosition);
        GD.Print($"Local tilemap coords: {localTilemapCoords}");
        var coords = tileMap.LocalToMap(localTilemapCoords);
        GD.Print($"Tilemap coords: {coords}");
        var td = tileMap.GetCellTileData(coords);
        if (td is null) return;
        
        //tileMap.TileSet.physics
        var vel = td.GetConstantLinearVelocity(2);
        GD.Print($"velocity: {vel}");
        var layerData = td.GetCustomDataByLayerId(0).As<Vector2>();
        // I can do whatever I want with this
        GD.Print($"Layer Data: {layerData}");

        _velocity = vel;
    }

    private void OnBodyExited(Node2D body)
    {
        if (body is not TileMapLayer tileMap) return;
        GD.Print($"Exited {body.Name}");
        
        _velocity = Vector2.Zero;
    }

    public override void EnterState(PlayerState state)
    {
        Enabled = true;
        GD.Print("Enabled conveyor");
    }

    public override void ExitState(PlayerState state)
    {
        Enabled = false;
        GD.Print("Disabled conveyor");
    }

    public override void Process(double delta)
    {
        
    }

    public override void PhysicsProcess(double delta)
    {
        if (Enabled && _velocity.Length() != 0)
        {
            CharacterBody.Velocity += _velocity;
            //GD.Print($"Applying velocity {_velocity} {CharacterBody.Velocity} ");
            
        }
    }
}