using System;
using UnityEngine;

public class EnemyController : MonoBehaviour
{
    enum State
    {
        Spawning,
        Moving,
        Dying
    }
    
    [Range(0f, 10f)]
    public float moveSpeed = 2f;
    
    public Material flashMaterial;
    public Material defaultMaterial;
    
    public AudioClip hitSound;
    public AudioClip deadSound;
    
    GameObject target;

    State state;
    
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
         //target = GameObject.Find("Player");
         // target = GameObject.FindGameObjectWithTag("Player");
         // state = State.Moving;
    }

    public void Spawn(GameObject target)
    {
        this.target = target;
        state = State.Spawning;
        GetComponent<Character>().Initalize();
        GetComponent<Animator>().SetTrigger("Spawn");
        Invoke("StartMoving", 1f);
        GetComponent<Collider2D>().enabled = false;
    }

    void StartMoving()
    {
        GetComponent<Collider2D>().enabled = true;
        state = State.Moving;
        
    }

    private void FixedUpdate()
    {
        if (state == State.Moving)
        {
            Vector2 direction = target.transform.position - transform.position;
            transform.Translate(direction.normalized * (moveSpeed * Time.fixedDeltaTime), Space.World);

            if (direction.x < 0)
            {
                GetComponent<SpriteRenderer>().flipX = true;
            }
            else if (direction.x > 0)
            {
                GetComponent<SpriteRenderer>().flipX = false;
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log("Hit");

        if (collision.tag == "Bullet")
        {
            float d = collision.gameObject.GetComponent<Bullet>().damage;
            
            if(GetComponent<Character>().Hit(d))
            {
                // 살아있을 때
                Flash();
                GetComponent<AudioSource>().PlayOneShot(hitSound);
                
            }
            else
            {
                // 죽었을 때
                Die();
                GetComponent<AudioSource>().PlayOneShot(deadSound);
            }
            
        }
    }

    void Flash()
    {
        GetComponent<SpriteRenderer>().material = flashMaterial;
        Invoke("AfterFlash", 0.5f);
    }

    void AfterFlash()
    {
        GetComponent<SpriteRenderer>().material = defaultMaterial;
    }

    void Die()
    {
        state = State.Dying;
        GetComponent<Animator>().SetTrigger("Die");
        
        // 일정 시간이 지난 후 호출하는 함수
        Invoke("AfterDying", 1.4f);
    }

    void AfterDying()
    {
        // Destroy(gameObject);
        gameObject.SetActive(false);
    }

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