using System;
using UnityEngine;

namespace Script.Gameplay.Connect
{
    // 只负责在场景中绘制连接线，并处理信号传递
    public class ConnectionLine : MonoBehaviour
    {
        [SerializeField] private MonoBehaviour monoSource;
        [SerializeField] private MonoBehaviour monoTarget;
        private IConnectable _output;
        private IConnectable _input;

        private LineRenderer line;

        private void Awake()
        {
            _output = monoSource as IConnectable;
            _input = monoTarget as IConnectable;

            line = GetComponent<LineRenderer>();

            if (_output != null && _input != null)
            {
                SetConnectable(_output, _input);
            }
        }

        public void SetConnectable(IConnectable output, IConnectable input)
        {
            _output = output;
            _input = input;
            _output.IsConnectedOutput = true;
            _input.IsConnectedInput = true;

            line.SetPositions(new Vector3[]
            {
                _output.GetPosition(),
                _input.GetPosition()
            });
        }

        public void ReceiveSignal(bool active)
        {
            SendSignal(active);
        }

        private void SendSignal(bool active)
        {
            _input.ReceiveSignal(active,this.gameObject);
        }

        private void OnDestroy()
        {
            if (_output != null)
            {
                _output.IsConnectedOutput = false;
            }

            if (_input != null)
            {
                _input.IsConnectedInput = false;
            }
        }
    }
}