using System;
using System.Collections;
using System.Collections.Generic;
using FMOD.Studio;
using Google.Apis.Http;
using UnityEngine;
using Ktyl.Util;
using TMPro;
using UnityEngine.Events;
using UnityEngine.InputSystem;

public class ArtefactControl : MonoBehaviour
{
    protected bool _canInteract;

    public Artefact data => _data;
    [SerializeField] private Artefact _data;
    public int artefactID => _artefactID;
    private int _artefactID;
    [SerializeField] private SerialInt _nearbyArtefactID;

    [SerializeField] private ArtefactSystem _artefacts;

    [SerializeField] private ArtefactInteractUI _ui;

    private void OnEnable()
    {
        _artefacts.RegisterArtefact(_data);
        SetNearby(false);
    }

    private void SetNearby(bool playerNearby)
    {
        _canInteract = playerNearby;
        _ui.gameObject.SetActive(playerNearby);
        _nearbyArtefactID.Value = playerNearby ? artefactID : -1;
    }

    protected virtual void Start()
    {
        _artefactID = data.artefactID;
        _canInteract = data.canInteract;

        EventHandler.current.onArtefactPickUp += PickUp;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (!other.gameObject.TryGetComponent(out PlayerInput playerInput))
        {
            Debug.LogError("collided with not the player ????", this);
            return;
        }
        
        SetNearby(true);
        
        _ui.Input = playerInput;
    }

    private void OnTriggerExit(Collider other)
    {
        SetNearby(false);
    }

    protected virtual void PickUp(int id)
    {
        if (id == this._artefactID)
        {
            if (_canInteract == true)
            {
                // artefact system informs other systems about found artefact
                _artefacts.FindArtefact(data);
            }
            
            if (this.gameObject != null)
            {
                data.Pickup();
                
                _nearbyArtefactID.Value = -1;
                _canInteract = false;
                EventHandler.current.ArtefactUI();
                Destroy(this.gameObject);
            }
        }
    }
}
