using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Mirror;
public class PushBox : NetworkBehaviour
{
    public int playersRequired;
    [SyncVar(hook =nameof(OnTouchersChanged))]
    public int playersTouching;
    public Vector3 detectorSize;
    public Text numberTxt;

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

    void Start()
    {
        UpdateText();
    }

    void Update(){
        
    }

    private void OnDrawGizmos() {
        Gizmos.DrawWireCube(transform.position, detectorSize);
    }

    [Server]
    public void UpdateNeighbourCount(){

    }

    [Server]
    public void UpdateNeighbourCount2()
    {
        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++;

            if(!Neighbours.Contains(targets[0])){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");
        }

        playersTouching = Neighbours.Count;

        GetComponent<Rigidbody2D>().constraints=((playersRequired - playersTouching) > 0) ? RigidbodyConstraints2D.FreezeAll : RigidbodyConstraints2D.FreezeRotation;
        
        UpdateText();
    }

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

    void UpdateText(int touchers)
    {
        numberTxt.text = (playersRequired - touchers).ToString();
    }


    void OnTouchersChanged(int oldValue, int newValue){
        UpdateText(newValue);
    }
}
