using UnityEngine;
using System.Collections.Generic;

public class Booster : MonoBehaviour {
	public static List<Booster> allBoosters;

	public float radius = 2f;

	public float boostDamage = 0;
	public float boostFireRate = 0;
	public float boostRange = 0;

	// Use this for initialization
	void Start () {
		if(allBoosters == null)
			allBoosters = new List<Booster>();

		allBoosters.Add(this);

		ApplyBoosts();

	}

	void OnDestroy() {
		allBoosters.Remove(this);
		ApplyBoosts(true);
	}

	public static void RemoveAllBoosts() {
		if(allBoosters == null)
			return;

		foreach(Booster b in allBoosters) {
			b.ApplyBoosts(true);
		}
	}

	public static void ApplyAllBoosts() {
		if(allBoosters == null)
			return;
		
		foreach(Booster b in allBoosters) {
			b.ApplyBoosts();
		}
	}

	void ApplyBoosts(bool remove = false) {
		Collider2D[] cols = Physics2D.OverlapCircleAll(this.transform.position, CurrentRadius());

		foreach(Collider2D col in cols) {
			Turret t = col.GetComponent<Turret>();

			if( t!= null ) {
				if(boostDamage > 0) {
					if(remove)
						t.damageBoost -= boostDamage;
					else
						t.damageBoost += boostDamage;
				}
				if(boostFireRate > 0) {
					if(remove)
						t.fireRateBoost -= boostFireRate;
					else
						t.fireRateBoost += boostFireRate;
				}
				if(boostRange > 0) {
					if(remove)
						t.rangeBoost -= boostRange;
					else
						t.rangeBoost += boostRange;
				}
			}
		}

	}

	public float CurrentRadius() {
		return radius + StatManager.current.bonusBoostRange;
	}

	public void TryApplyBoosts(Turret t) {
		Collider2D[] cols = Physics2D.OverlapCircleAll(this.transform.position, CurrentRadius());
		
		foreach(Collider2D col in cols) {
			Turret t2 = col.GetComponent<Turret>();
			
			if( t2!= null && t2 == t ) {
				if(boostDamage > 0)
					t.damageBoost += boostDamage;
				if(boostFireRate > 0)
					t.fireRateBoost += boostFireRate;
				if(boostRange > 0)
					t.rangeBoost += boostRange;
			}
		}
		
	}
	

}
