using Game.Resources;
using Godot;

namespace Game;

[SceneTree]
public partial class MeetingPhysicsBox : RigidBody2D
{
    private Vector2 _dragTarget;
    private bool _isDragging;

    private bool _mouseInside;

    [Export]
    public MeetingResource MeetingResource { get; set; } = new DummyMeetingResource();

    public override void _Ready()
    {
        FreezeMode = FreezeModeEnum.Kinematic;

        MouseEntered += () =>
        {
            GD.Print("Mouse Entered");
            _mouseInside = true;
            CanSleep = false;
        };
        MouseExited += () =>
        {
            _mouseInside = false;
            CanSleep = true;
        };

        MeetingControlGfx.MeetingResource = MeetingResource;
    }

    public override void _UnhandledInput(InputEvent @event)
    {
        using (@event)
        {
            if (@event is InputEventMouse mouseEvent)
                if (_mouseInside)
                    if (mouseEvent.IsPressed() && mouseEvent.ButtonMask == MouseButtonMask.Left)
                    {
                        GD.Print("Start Dragging");
                        StartDragging();
                    }
        }
    }

    public override void _PhysicsProcess(double delta)
    {
        _dragTarget = GetGlobalMousePosition();
    }

    public override void _IntegrateForces(PhysicsDirectBodyState2D state)
    {
        if (!_isDragging)
            return;

        var t = state.Transform;
        t.Origin = _dragTarget;

        state.Transform = t;
        state.LinearVelocity = Vector2.Zero;
        state.AngularVelocity = 0;
    }

    private void StartDragging()
    {
        LinearVelocity = Vector2.Zero;
        AngularVelocity = 0;
        RotationDegrees = 0;

        var meetingControl = Instantiator.Instantiate<MeetingControl>();
        meetingControl.MeetingPhysicsBox = this;

        GetParent().AddChild(meetingControl);
        meetingControl.StartDrag();

        meetingControl.Position = new Vector2(-5000, -5000);

        GetParent().RemoveChild(this);
        _mouseInside = false;
    }
}
