using System;
using Core;
using Gameplay.Player;
using Script.Gameplay.Connect;
using TMPro;
using UnityEngine;

namespace UI
{
    public class PlayerConnectViewer : UIBase
    {
        public TMP_Text inputText;
        public TMP_Text outputText;
        private PlayerConnectController _playerConnectController;
        private PlayerWatchModeController _playerWatchModeController;

        private void Awake()
        {
            ControllerLocator.Instance.TryGetWait<PlayerConnectController>(OnGetConnectController);
            ControllerLocator.Instance.TryGetWait<PlayerWatchModeController>(OnGetWatchModeController);
        }
        
        private void OnGetConnectController(PlayerConnectController controller)
        {
            _playerConnectController = controller;
            _playerConnectController.OnSetInputTarget += UpdateInputText;
            _playerConnectController.OnSetOutputTarget += UpdateOutputText;
            UpdateInputText(null);
            UpdateOutputText(null);
        }
        
        private void UpdateInputText(IConnectable input)
        {
            string text = input != null ? input.GetConnectableName() : "None";
            if (inputText != null)
            {
                inputText.text = "Input: " + text;
            }
        }
        
        private void UpdateOutputText(IConnectable output)
        {
            string text = output != null ? output.GetConnectableName() : "None";
            if (outputText != null)
            {
                outputText.text = "Output: " + text;
            }
        }
        
        private void OnGetWatchModeController(PlayerWatchModeController controller)
        {
            _playerWatchModeController = controller;
            _playerWatchModeController.OnEnterWatchMode += (mode) =>
            {
                if (mode == WatchMode.Outside) Show();
            };
            _playerWatchModeController.OnExitWatchMode += (mode) =>
            {
                if (mode == WatchMode.Outside) Hide();
            };
        }
    }
}