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

namespace RollingRockRumble {
    public class SpikeHandler : MonoBehaviour {

        private Vector2 explosionPowerFactor = new Vector2(0.75f,5f);
        public GameObject prefabParticleSpike;

        private float autoExplodeTime;
        private float duration = 10f;



        void Start() {
            autoExplodeTime = Time.time + duration;
        }



        void Update() {
            if (autoExplodeTime < Time.time) {
                DestroySpike(false);
            }
        }



        void OnCollisionEnter2D(Collision2D coll) {
            if (coll.gameObject.tag == "Boulder") {
                coll.gameObject.GetComponent<Rigidbody2D>().velocity += new Vector2((coll.gameObject.transform.position.x - transform.position.x) * explosionPowerFactor.x,
                                                                                    (coll.gameObject.transform.position.y - transform.position.y) * explosionPowerFactor.y);
                DestroySpike(true);
                coll.gameObject.GetComponent<RockHandler>().DecreaseDiameter();
            }
            if ((coll.gameObject.tag == "Wall") ||
                (coll.gameObject.tag == "Slope") ||
                (coll.gameObject.tag == "Spawner")) {
                Destroy(this.GetComponent<Rigidbody2D>());
            }
        }



        public void DestroySpike(bool isDestroyedByPlayer) {
            if(isDestroyedByPlayer){
                AudioSource tempSFX = GameObject.Find("SFXSpikeExplode").GetComponent<AudioSource>();
                tempSFX.transform.position = transform.position;
                tempSFX.Play();
            }
            Instantiate(prefabParticleSpike, transform.position, Quaternion.identity);
            Destroy(this.gameObject);
        }
    }
}
