using System.Collections;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public ParticleSystem explosion;
    public ParticleSystem explosionDebris;
    public Transform landingPoint;
    public GameObject body;
    
    [Header("Audio")]
    public AudioSource sfx;
    [SerializeField] private AudioClip enemyDeath;
    [SerializeField] private AudioClip enemyHit;
    
    [Header("Enemy Stats")]
    public float flyingSpeed;
    public SphereCollider collider; 
    [SerializeField] private float maxHP = 1;
    [SerializeField] private float damage = 1;
    private float _health;

    private void Start()
    {
        _health = maxHP;
    }
    
    public void SetLandingPoint(Transform landingPoint)
    {
        this.landingPoint = landingPoint;
        gameObject.transform.LookAt(landingPoint);
    }

    void SpawnFinished()
    {
        StartCoroutine("Launch", 0.01f);
    }

    IEnumerator Launch()
    {
        yield return new WaitForSeconds(.1f);
        gameObject.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * flyingSpeed;
    }

    public void IsShot(float distance, float turretDamage)
    {
        float destroyDelay = Mathf.Sqrt(distance)/(500/5);
        _health -= turretDamage;
        if (_health <= 0)
        {
            StartCoroutine(Destroy(destroyDelay));
            SoundManager.Instance.PlaySfx(sfx, enemyDeath);
        }
        else
        {
            SoundManager.Instance.PlaySfx(sfx, enemyHit);
        }
    }

    private IEnumerator Destroy(float waitTime)
    {
        GameManager.Instance.GainPoints(maxHP);
        gameObject.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * (flyingSpeed / 3);
        yield return new WaitForSeconds(waitTime);
        body.SetActive(false);
        explosion.Emit(100);
        explosionDebris.Emit(40);
        yield return new WaitForSeconds(.1f);
        collider.enabled = false;
        yield return new WaitForSeconds(2f);
        Destroy(gameObject);
    }

    public float DamageDealt()
    {
        return damage;
    }
}
