using System;
using Godot;

namespace Hellswipers.Game;

public partial class Game {
    private Vector2? _swipeStart;
    
    private void CalcSwipe(Vector2 end) {
        if (!_swipeStart.HasValue)
            return;
        var delta = end - _swipeStart.Value;
        _swipeStart = null;

        var deltaAbs = delta.Abs();
        var biggest = Math.Max(deltaAbs.X, deltaAbs.Y);
        if (biggest < 50)
            return;

        HandleInput(deltaAbs.X > deltaAbs.Y
            ? (delta.X > 0 ? Arrow.Dirs.Right : Arrow.Dirs.Left)
            : (delta.Y > 0 ? Arrow.Dirs.Down : Arrow.Dirs.Up)
        );
    }
	
    public override void _UnhandledInput(InputEvent ev) {
        if (ev is InputEventMouseButton evm) {
            if (ev.IsPressed())
                _swipeStart = evm.Position;
            else
                CalcSwipe(evm.Position);
        } else {
            if (ev.IsActionPressed("key_up"))
                HandleInput(Arrow.Dirs.Up);
            else if (ev.IsActionPressed("key_down"))
                HandleInput(Arrow.Dirs.Down);
            else if (ev.IsActionPressed("key_left"))
                HandleInput(Arrow.Dirs.Left);
            else if (ev.IsActionPressed("key_right"))
                HandleInput(Arrow.Dirs.Right);
            else if (ev.IsActionPressed("escape"))
                GetTree().ChangeSceneToPacked(ResourceLoader.Load<PackedScene>("res://main_menu/main_menu.tscn"));
        }
    }

}