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

public class GhostKing : MonoBehaviour
{
    private bool isPlayerNear = false;
    GameObject player = null;
    private void OnTriggerEnter2D(Collider2D _col)
    {
        if(_col.gameObject.CompareTag("Player"))
        {
            isPlayerNear = true;
            player = _col.gameObject;
            this.transform.GetChild(0).GetChild(0).gameObject.SetActive(true);
        }
    }
    private void OnTriggerExit2D(Collider2D _col)
    {
        if (_col.gameObject.CompareTag("Player"))
        {
            isPlayerNear = false;
            player = null;
            this.transform.GetChild(0).GetChild(0).gameObject.SetActive(false);
        }
    }

    private void Update()
    {
        if(isPlayerNear)
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                StartCoroutine( OnClick() );
            }
        }
    }
    private IEnumerator OnClick()
    {
        if(player.TryGetComponent(out HasGhost hg))
        {
            hg.Ghosts = 1;
        }
        if(player.TryGetComponent(out Animator an))
        {
            an.SetInteger("State", 3);
            if (player.TryGetComponent(out PlayerMove pm)) pm.enabled = false;
            yield return new WaitForSeconds(1f);
            if(pm != null) pm.enabled = true;
            an.SetInteger("State", 1);
        }
        Destroy(this.gameObject, 4f);
        player.GetComponent<SpriteRenderer>().enabled = false;
        player.GetComponent<PlayerMove>().enabled = false;
        player.transform.Find("UnityParticleSystem").GetComponent<ParticleSystem>().Play();
        this.GetComponent<SpriteRenderer>().enabled = false;
        yield return new WaitForSeconds(2f);
        SceneManager.LoadScene("MainMenu");
    }
}
