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

public class ButtonPuller : MonoBehaviour
{

    GameObject[] playersKeeper;
    Collider2D[] playerCols;
    public ChangeLog[] changes;
    public ChangeLog[] revert;
    bool isReverted;
    Collider2D myCollidor;
    bool isWalkAway = true;
    public bool[] isToActive;
    public float redius;
	// Use this for initialization
	void Start ()
    {
        FindPlayers();
        myCollidor = this.GetComponent<Collider2D>();
    }
	
	// Update is called once per frame
	void Update ()
    {
       if(!isWalkAway)
        {
            CalcAway();
        }
       else
        {
            for (int i = 0; i<3; i ++)
            {
                print(playerCols.Length);
                if (myCollidor.IsTouching(playerCols[i])&&isToActive[i])
                {
                    isWalkAway = false;
                    ActButton();
                }
            }
        }

	}
    void ActButton()
    {
        if(isReverted)
        {
            foreach (ChangeLog theChange in revert)
            {

                theChange.changeThis.ChangeColor(theChange.changeTo);
            }
        }
        else
        {
            foreach (ChangeLog theChange in changes)
            {

                theChange.changeThis.ChangeColor(theChange.changeTo);
            }
        }
        isReverted = !isReverted;
    }
    public void FindPlayers()
    {
        playersKeeper = new GameObject[3];
        playerCols = new Collider2D[3];
        GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
        int playerPlace;
        for (int i = 0; i< 3;i++)
        {
            playerPlace = (int)players[i].GetComponent<MovmentControl>().avaterColor;
            playersKeeper[playerPlace] = players[i];
            playerCols[playerPlace] = players[i].GetComponent<Collider2D>();
        }
    }
    void CalcAway()
    {
        float minDis = float.MaxValue;
        for (int i = 0; i < 3; i++)
        {
            if (isToActive[i])
            {
                minDis = Mathf.Min(minDis, Vector2.Distance(this.transform.position, playersKeeper[i].transform.position));
            }
        }
        if(minDis>redius)
        {
            isWalkAway = true;
        }
    }
}
