using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BeaconManager : MonoBehaviour
{
    public System.Action<GameObject> OnBeaconSpawned;

    [SerializeField] GameObject BeaconPrefab;
    [SerializeField] Camera Camera;
    [SerializeField] LayerMask ObstacleMask;
    [SerializeField] float GridSize = 3f;

    private PlayerData player;

    private int[] coords = new int[2];

    public static System.Action<int[]> OnBeaconPlaced;

    private void Awake()
    {
        player = FindObjectOfType<PlayerData>();
        PDAEnable.OnPDAStateChange += OnPDAChanged;
    }

    private void OnDestroy()
    {
        PDAEnable.OnPDAStateChange -= OnPDAChanged;
    }

    private void OnPDAChanged(bool pdaEnabled)
    {
        enabled = !pdaEnabled;
    }

    private void Update()
    {
        if (!Input.GetMouseButtonDown(0)) return;

        //check beacon is in inventory

        if (player.UseItemInInventory(BeaconPrefab.GetComponent<Item>().item, 1))
        {
            PlaceBeacon();
            OnBeaconPlaced?.Invoke(coords);
        }

        
    }

    private void PlaceBeacon()
    {
        if (!Physics.Raycast(Camera.ScreenPointToRay(Input.mousePosition), out RaycastHit hitInfo, 999f, ObstacleMask)) return;

        float x = Mathf.Round(hitInfo.point.x / GridSize) * GridSize;
        float y = Mathf.Round(hitInfo.point.z / GridSize) * GridSize;
        Vector3 position = new Vector3( x, 0, y);

        GameObject beacon = Instantiate(BeaconPrefab, position, Quaternion.identity, transform);

        coords[0] = (int)x;
        coords[1] = (int)y;

        OnBeaconSpawned?.Invoke(beacon);

    }
}
