using Godot;
using System;
using System.Collections.Generic;
using RustyOptions;

namespace Movementtests.systems;


public partial class WallHugSystem : Node3D
{
    [Signal]
    public delegate void WallDetectedEventHandler();
    
    private List<RayCast3D> _raycasts;
    
    public void Init()
    {
        _raycasts = new List<RayCast3D>();
        _raycasts.Add(GetNode<RayCast3D>("front"));
        _raycasts.Add(GetNode<RayCast3D>("back"));
        _raycasts.Add(GetNode<RayCast3D>("left"));
        _raycasts.Add(GetNode<RayCast3D>("right"));
    }

    public override void _PhysicsProcess(double delta)
    {
        base._PhysicsProcess(delta);
        if (IsWallHugging())
            EmitSignal(SignalName.WallDetected);
    }

    public bool IsWallHugging()
    {
        foreach (RayCast3D raycast in _raycasts)
        {
            if (raycast.IsColliding())
            {
                return true;
            }
        }
        return false;
    }

    public Option<Vector3> GetWallNormal()
    {
        foreach (RayCast3D raycast in _raycasts)
        {
            if (raycast.IsColliding())
            {
                return raycast.GetCollisionNormal().Some();
            }
        }
        return Option<Vector3>.None;
    }
}
