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

public class SpiritBall : MonoBehaviour{

    public float spiritballLifeTime = 2f;

    public GameObject particles;
    public float particleLifetime = 1f;

    public GameObject deathEffectPrefab;
    public float deathEffectLifetime;

    CinemachineVirtualCamera vCam;
    PlayerController player;
    bool playerCollided;

    // Start is called before the first frame update
    void Start(){
        Invoke("DestroyFireball", spiritballLifeTime);
    }

    // Update is called once per frame
    void Update(){
        
    }

    void DestroyFireball(){
        ScreenshakeHandler.AddScreenShake(3, 5, .1f);

        particles.transform.parent = null;
        particles.GetComponent<ParticleSystem>().Stop();
        Destroy(particles, particleLifetime);

        var deathEffect = Instantiate(deathEffectPrefab, transform.position, transform.rotation);
        Destroy(deathEffect, deathEffectLifetime);

        if (!playerCollided){
            player.active = true;
            vCam.Follow = player.gameObject.transform;
        }

        Destroy(gameObject);
    }

    public void SetCamera(CinemachineVirtualCamera camera, PlayerController from){
        vCam = camera;
        player = from;
    }

    void OnCollisionEnter2D(Collision2D col){
        if(col.gameObject.tag == "Player"){
            vCam.Follow = col.gameObject.transform;
            col.gameObject.GetComponent<PlayerController>().active = true;
            playerCollided = true;
            CancelInvoke("DestroyFireball");
            DestroyFireball();
        }

        if(col.gameObject.tag == "Enemy"){
            vCam.Follow = col.gameObject.transform;
            col.gameObject.GetComponent<EnemyController>().Die();
            CancelInvoke("DestroyFireball");
            DestroyFireball();
        }
    }
}
