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

public class Bomb : MonoBehaviour {
    Animator animator;
    public float radius = 50.0F;
    public float power = 10.0F;
    public GameObject[] players;

    // Use this for initialization
    void Start () {
		players = GameObject.FindGameObjectsWithTag ("Player");
        GetComponent<SphereCollider>().enabled = false;
        animator = gameObject.GetComponent<Animator>();
        StartCoroutine(explode());
        StartCoroutine(triggerOn());
	}
	
	// Update is called once per frame
	void Update () {

        
    }



    public static void AddExplosionForce(Rigidbody body, float expForce, Vector3 expPosition, float expRadius, float uplift)
    {
		var dir = (body.transform.position - (expPosition + new Vector3(0, -.5f, 0)));
        float calc = 1 - (dir.magnitude / expRadius);
        if (calc <= 0)
        {
            calc = 0;
        }
        
        Vector3 force = dir.normalized * expForce * calc;
        body.AddForce(force);
        //else if (force.x <= 0) body.AddForce(force + new Vector3(-1000, 100, 0));
        /*
        float upliftWearoff = 1 - uplift / expRadius;
        Vector3 upliftForce = Vector2.up * expForce * upliftWearoff;
        body.AddForce(upliftForce);
        */
    }

    private IEnumerator triggerOn()
    {
        yield return new WaitForSeconds(0.5f);

        GetComponent<SphereCollider>().enabled = true;
    }

    private IEnumerator explode()
    {
        
        yield return new WaitForSeconds(1.0f);
		AudioController.AC.playExp ();
        animator.SetBool("Explode", true);
        GetComponent<Rigidbody>().velocity = Vector3.zero;
        foreach (GameObject player in players) {
            Vector3 pos = transform.position;
            float dist = Vector3.Distance(pos, player.transform.position);
            if (dist <= radius)
            {
                player.GetComponent<MailboyMove>().Hit2();
                AddExplosionForce(player.GetComponent<Rigidbody>(), power * 100, pos, radius, 0.0f);
            }
        }
        Destroy(gameObject, 0.6f);
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player")) {
            animator.SetBool("Explode", true);
            StopAllCoroutines();
            GetComponent<Rigidbody>().velocity = Vector3.zero;
            foreach (GameObject player in players)
            {
                Vector3 pos = transform.position;
                float dist = Vector3.Distance(pos, player.transform.position);
                if (dist <= radius) {
                    player.GetComponent<MailboyMove>().Hit2();
                    AddExplosionForce(player.GetComponent<Rigidbody>(), power * 100, pos, radius, 0.0f);
                }
                    
            }

            Destroy(gameObject, 0.6f);
        }
    }
}
