using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.InputSystem;

public class UnitSelectionHandler : MonoBehaviour
{
    [SerializeField] private LayerMask _layerMask;
    private Camera _mainCamera;

    private readonly List<Unit> _selectedUnits = new();

    private void Start()
    {
        _mainCamera = Camera.main;
    }

    private void Update()
    {
        if (Mouse.current.leftButton.wasPressedThisFrame)
        {
            ClearSelectedUnits();
            //Start selection area
        }
        else if (Mouse.current.leftButton.wasReleasedThisFrame)
        {
            ClearSelectionArea();
        }
    }

    private void ClearSelectedUnits()
    {
        foreach (Unit selectedUnit in _selectedUnits)
        {
            selectedUnit.DeSelect();
        }

        _selectedUnits.Clear();
    }

    private void ClearSelectionArea()
    {
        Ray ray = _mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());

        if (!Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, _layerMask)) return;

        if (!hit.collider.TryGetComponent(out Unit unit)) return;

        if (!unit.isOwned) return;

        _selectedUnits.Add(unit);

        foreach (Unit selectedUnit in _selectedUnits)
        {
            selectedUnit.Select();
        }
    }
}