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

public class TowerGameController : MonoBehaviour {

	public static TowerGameController instance;


	[SerializeField] List<Rigidbody2D> balls;
	public List<GameObject> towers;
	[SerializeField] float strenght, pow;

	void Awake(){
		if (instance == null) {
			instance = this;
			balls = new List<Rigidbody2D>();
			towers = new List<GameObject>();
		} else {
			Destroy (gameObject);
		}
	}

	void Start(){

	}

	void FixedUpdate () {

		foreach (Rigidbody2D ball in balls) {
			foreach (GameObject tower in towers) {
                if (tower.activeSelf)
                {
                    Vector3 direction = (ball.transform.position - tower.transform.position).normalized;
                    direction = new Vector3(direction.x * 0.8f, direction.y, 0f);
                    //ball.AddForce (strenght * direction / Mathf.Pow((ball.transform.position - tower.position).sqrMagnitude,pow));

                    /*
                    if(ball.GetComponent<PhysicBall>().isblue() && tower.GetComponent<Tower>().isBlue())
                        ball.AddForce (strenght * direction / Mathf.Pow((ball.transform.position - tower.position).sqrMagnitude,pow));
                    else if(!ball.GetComponent<PhysicBall>().isblue() && !tower.GetComponent<Tower>().isBlue())
                        ball.AddForce (strenght * direction / Mathf.Pow((ball.transform.position - tower.position).sqrMagnitude,pow));
                    */

                    if (tower.GetComponent<Tower>().isBlue())
                        ball.AddForce(strenght * direction / Mathf.Pow((ball.transform.position - tower.transform.position).sqrMagnitude, pow));
                    else
                        ball.AddForce(strenght * -direction / Mathf.Pow((ball.transform.position - tower.transform.position).sqrMagnitude, pow));
                }
              
            }
		}
	}

	public bool AddTower(GameObject tower){
        if (tower.transform.position.x < 7.5 && tower.transform.position.x > -7.5 
            && tower.transform.position.y > -4.5 && tower.transform.position.y < 4.5)
        {
            StartCoroutine(AddTowerDelay(tower, 1f));
            return true;
        }
        return false;
    }



    IEnumerator AddTowerDelay(GameObject tower, float delayTime)
    {
        yield return new WaitForSeconds(delayTime);
        if (!towers.Contains(tower))
        {
            towers.Add(tower);
        }
    }

    public void AddBall(Rigidbody2D ball){
			balls.Add (ball);
	}

	public void RemoveTower(GameObject tower){
        if (!towers.Remove(tower))
        {

        }
    }

	public void RemoveBall(Rigidbody2D ball){
		balls.Remove (ball);
	}

	public void IncreasePower(){
		strenght += 0.25f;
	}

	public void RedistributeTowers(){
		//foreach (Transform tower in towers) {
			//tower.transform.position = new Vector3 (Random.Range (-7f, 7f), Random.Range (-4f, 4f), 0);
		//}
	}
}
