using System;
using UnityEngine;
using System.Collections.Generic;
using Core;

namespace Script.Gameplay.Connect
{
    [Serializable]
    public class PreviousConnection
    {
        public int PreConnectionID;
        public MonoBehaviour source;
        public MonoBehaviour target;
    }
    public class ConnectionLineManager : MonoSingleton<ConnectionLineManager>
    {
        [SerializeField] private GameObject linePrefab; 
        [SerializeField]private List<PreviousConnection> preConnectionLines = new List<PreviousConnection>();
        private List<ConnectionLine> connectionLines = new List<ConnectionLine>();

        private void Start()
        {
            GeneratePreviousConnectionLines(preConnectionLines);
        }

        public ConnectionLine GenerateConnectionLine(IConnectable a, IConnectable b)
        {
            GameObject lineObject = Instantiate(linePrefab, this.transform);
            ConnectionLine connectionLine = lineObject.GetComponent<ConnectionLine>();
            if (connectionLine != null)
            {
                connectionLine.SetConnectable(a, b);
                connectionLines.Add(connectionLine);
                return connectionLine;
            }
            return null;
        }

        public void CutTargetConnectionLines(IConnectable target)
        {
            List<ConnectionLine> linesToRemove = new List<ConnectionLine>();
            foreach (var line in connectionLines)
            {
                if (line != null && (line.Equals(target)))
                {
                    linesToRemove.Add(line);
                }
            }
            foreach (var line in linesToRemove)
            {
                connectionLines.Remove(line);
                Destroy(line.gameObject);
            }
        }
        
        public void GeneratePreviousConnectionLines(List<PreviousConnection> previousConnections)
        {
            foreach (var preConnection in previousConnections)
            {
                IConnectable source = preConnection.source as IConnectable;
                IConnectable target = preConnection.target as IConnectable;
                if (source != null && target != null)
                {
                    GenerateConnectionLine(source, target);
                }
                else
                {
                    Debug.Log(preConnection.PreConnectionID + " connection failed to load.");
                }
            }
        }
    }
}