using UnityEngine;
using System.Collections;
using System.Threading;

public class ClearEnemyProjectilesRing : MonoBehaviour
{

    public float RingExpandTime;
    public float fClearProjectilesRange = 100.0f;
    private SpriteRenderer mySpriteRenderer;

    void Awake()
    {
        mySpriteRenderer = GetComponent<SpriteRenderer>();
        mySpriteRenderer.enabled = false;

    }

	// Use this for initialization
	void Start () 
    {
	
	}
	
	// Update is called once per frame
	void Update ()
	{

	}

    public void ExpandRing()
    {
        StartCoroutine(ExpandRingCoroutine(RingExpandTime));

        TM_Projectile[] slowAssFindCall = FindObjectsOfType<TM_Projectile>();


        for (int t = 0; t < slowAssFindCall.Length; t++)
        {
            TM_Projectile p = slowAssFindCall[t];
            if (p.gameObject.layer == LayerMask.NameToLayer("EnemyProjectile"))
            {
                Vector3 vToProj = p.transform.position - transform.position;
                vToProj.z = 0;

                if (vToProj.sqrMagnitude > fClearProjectilesRange*fClearProjectilesRange)
                    continue;

                vToProj.Normalize();
                p.bLetSomeoneElseMoveMe = false;
                p.fSpeed = Random.Range(50.0f, 80.0f);
                p.vDirection = vToProj;
                Destroy(p.gameObject, 0.5f);
            }
        }

        EnemyAI[] slowAssEnemySearch = FindObjectsOfType<EnemyAI>();
        for (int t = 0; t < slowAssEnemySearch.Length; t++)
        {
            EnemyAI e = slowAssEnemySearch[t];
            Vector3 vToProj = e.transform.position - transform.position;
            vToProj.z = 0;
            if (vToProj.sqrMagnitude < 30.0f*30.0f)
            {
                vToProj.Normalize();
                e.HitByClearingRing(vToProj);
            }
        }

    }

    private IEnumerator ExpandRingCoroutine(float fExpandTime)
    {
        mySpriteRenderer.enabled = true;
        Material mat = mySpriteRenderer.material;
        float fTime = 0;
        while (fTime < fExpandTime)
        {
            mat.SetFloat("_RingRadius", Mathf.Lerp(0.0f, 0.5f, fTime/fExpandTime));
            fTime += Time.deltaTime;
            yield return null;
        }
        mat.SetFloat("_RingRadius", 0f);
        mySpriteRenderer.enabled = false;

    }
}
