using UnityEngine;
using TMPro;
using System.Diagnostics;

[RequireComponent(typeof(TMP_InputField))]
public class InputFieldManager : MonoBehaviour
{
    private TMP_InputField _inputField = null;
    private Process _keyboard;

    private void Start()
    {
        _inputField = GetComponent<TMP_InputField>();
        if (_inputField != null)
        {
            _inputField.onSelect.AddListener(OnInputSelect);
            _inputField.onDeselect.AddListener(OnInputDeselect);
        }
        else
        {
            UnityEngine.Debug.LogError("Please add the TMP_InputField component to the object", this);
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Return)) CloseKeyboard(); // If enter key pressed, close keyboard
    }

    private void CloseKeyboard()
    {
        KeyboardManager.HideTouchKeyboard();
    }

    private void LaunchKeyboard()
    {
        KeyboardManager.ShowTouchKeyboard();
    }

    private void OnInputSelect(string pSelectionEvent)
    {
        LaunchKeyboard();
    }

    private void OnInputDeselect(string pSelectionEvent)
    {
        CloseKeyboard();
    }

    private void OnDestroy()
    {
        CloseKeyboard();
        _inputField.onSelect.RemoveListener(OnInputSelect);
        _inputField.onDeselect.RemoveListener(OnInputDeselect);
    }
}
