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

namespace UI
{
    public class PlayerConnectViewer : UIBase
    {
        public TMP_Text pointBText;
        public TMP_Text pointAText;
        private PlayerConnectController _playerConnectController;
        private PlayerWatchModeController _playerWatchModeController;

        protected override void Awake()
        {
            base.Awake();
            ControllerLocator.Instance.TryGetWait<PlayerConnectController>(OnGetConnectController);
            ControllerLocator.Instance.TryGetWait<PlayerWatchModeController>(OnGetWatchModeController);
        }
        
        private void OnGetConnectController(PlayerConnectController controller)
        {
            _playerConnectController = controller;
            _playerConnectController.OnSetPointB += UpdateInputText;
            _playerConnectController.OnSetPointA += UpdateOutputText;
            UpdateInputText(null);
            UpdateOutputText(null);
        }
        
        private void UpdateInputText(IConnectable input)
        {
            string text = input != null ? input.GetConnectableName() : "None";
            if (pointBText != null)
            {
                pointBText.text = "pointB: " + text;
            }
        }
        
        private void UpdateOutputText(IConnectable output)
        {
            string text = output != null ? output.GetConnectableName() : "None";
            if (pointAText != null)
            {
                pointAText.text = "pointA: " + text;
            }
        }
        
        private void OnGetWatchModeController(PlayerWatchModeController controller)
        {
            _playerWatchModeController = controller;
            _playerWatchModeController.OnEnterWatchMode += (mode) =>
            {
                if (mode == WatchMode.Outside) Show();
            };
            _playerWatchModeController.OnExitWatchMode += (mode) =>
            {
                if (mode == WatchMode.Outside) Hide();
            };
        }
    }
}