using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Mirror;
public class PushBox : NetworkBehaviour
{
    public int playersRequired;
    public Text numberTxt;

    public List<NetPlayer> DTP;
    public List<NetPlayer> Neighbours;
    public List<NetPlayer> targets;
    public List<NetPlayer> scannedList;

    void Start()
    {
        UpdateText();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        NetPlayer player = col.collider.GetComponent<NetPlayer>();
        if (player != null)
        {
            if (!DTP.Contains(player))
            {
                DTP.Add(player);
                UpdateNeighbourCount();
                
            }
        }
    }

    void OnCollisionExit2D(Collision2D col)
    {
        NetPlayer player = col.collider.GetComponent<NetPlayer>();
        if (player != null)
        {
            if (DTP.Contains(player))
            {
                DTP.Remove(player);
                UpdateNeighbourCount();                
            }
        }
    }


    public void UpdateNeighbourCount()
    {
        targets = new List<NetPlayer>();
        Neighbours = new List<NetPlayer>();
        scannedList= new List<NetPlayer>();

        targets.AddRange(DTP);

        int failCount = 0;
        while(targets.Count > 0 && failCount < 50){
            failCount++;

            Neighbours.Add(targets[0]);
            scannedList.Add(targets[0]);
            foreach(NetPlayer neighbour in targets[0].touchingNeighbours){
                if(!scannedList.Contains(neighbour)){
                    targets.Add(neighbour);
                }
            }
            scannedList.Add(targets[0]);
            targets.RemoveAt(0);
        }

        if(failCount >= 50){
            Debug.LogError("Fail switch triggered");
        }

        GetComponent<Rigidbody2D>().simulated=((playersRequired - Neighbours.Count) > 0);
        
        UpdateText();
    }

    void UpdateText()
    {
        numberTxt.text = (playersRequired - Neighbours.Count).ToString();
    }
}
