using UnityEngine;
using System.Collections;


public class TileScript : MonoBehaviour {
    [SerializeField] private Renderer renderer;
    [SerializeField] private Animator animator;

    private Color startColor;
    private GameObject particlesystem;
    private ParticleSystem ps;

    private void Awake() {
        if (renderer == null) {
            return;
        }

        startColor = renderer.sharedMaterial.color;
    }

    public void SetEnabled(bool isOn) {
        if (renderer != null) {
            if (isOn) {
                renderer.material.color = startColor;
            } else {
                renderer.material.color = new Color(startColor.r / 2f, startColor.g / 2f, startColor.b / 2f, 0.5f);
            }
        }

        if (animator != null) {
            //burning particlesystem specific for spikes
            if(this.gameObject.name.Contains("SpikeTrapPrefab") && !isOn)
            {
                if(particlesystem != null || ps != null)
                {
                    DestroyImmediate(particlesystem);
                    ps = null;
                }

                particlesystem = Instantiate(Resources.Load("Prefabs/BurningParticles"), this.gameObject.transform.position, Quaternion.identity) as GameObject;
                ps = particlesystem.GetComponent<ParticleSystem>();
                StartCoroutine(KillPS());
            }
            animator.SetBool("IsOn", isOn);
        }
    }

    IEnumerator KillPS()
    {
        if (ps == null) {
            yield break;
        }

        while (ps.IsAlive())
        { 
            yield return null;
            if (ps == null) {
                yield break;
            }
        }

        ps = null;
        DestroyImmediate(particlesystem);
    }
}
