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

public class Bomb : Grabable
{
    [SerializeField] private Color _alertColor;
    [SerializeField] private Renderer _renderer;
    [SerializeField] private GameObject _particlePrefab;
    [SerializeField] private Transform _fuse;
    [SerializeField] private float _fuseTime = 4f;
    [SerializeField] private float _detroyRadius = 2f;
    [SerializeField] private float _pushRadius = 7f;

    private float _lifeStart;

    public override void Setup(Vector3 force)
    {
        base.Setup(force);
    }

	// Use this for initialization
    public  void Start()
    {
        _lifeStart = Time.time;
	}
	
	// Update is called once per frame
    public override void Update()
    {
        base.Update();

        float percentage = (Time.time - _lifeStart) / _fuseTime;
        _fuse.transform.localScale = new Vector3(1, 1f - percentage, 1);

        _renderer.material.color = Color.Lerp(Color.black, _alertColor, Mathf.Sin(Mathf.Pow(percentage, 2f) * 40 * Mathf.PI));

        //_alertColor

        if (Time.time > _lifeStart + _fuseTime)
            Explode();
	}


    void Explode()
    {
        SoundController.Instance.PlaySound(SoundController.Instance._explosion);

        List<Package> destroyed = new List<Package>();

        // particle do stuff, unparent + go
        for (int i = 0; i < GameController.Instance.Packages.Count; i++ )
        {
            Vector3 delta = GameController.Instance.Packages[i].transform.position - transform.position;
            delta.y -= 0.3f;

            if (delta.magnitude < _detroyRadius)
                destroyed.Add(GameController.Instance.Packages[i]);
            else
            {
                float force = 1400f;
                GameController.Instance.Packages[i].RigidBody.AddExplosionForce(force, transform.position, _pushRadius, 3.0f);
            }
        }

        for (int i = 0; i < destroyed.Count;i++ )
        {

            destroyed[i].DestroyMe(true);
        }


        Instantiate(_particlePrefab, transform.position, Quaternion.identity);

        Destroy(this.gameObject);
    }



}
