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

public class SoliderL : MonoBehaviour
{
    Animator animator;  // BS의 애니메이터 컴포넌트
    public bool isAttacking = false;  // 공격 중인지 확인하는 플래그
    Rigidbody2D rb;
    public float speed = 1.5f;
    public int health;
    bool isDamage; // 무적 타임 처리

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();  // Animator 컴포넌트 가져오기
    }

    void OnHit()
    {
        // Health Down
        health--;
        animator.SetTrigger("doHit");
        Invoke("ReturnSprite", 0.2f);
        if (health <= 0)
        {
            animator.SetTrigger("doDie");
            Destroy(gameObject, 2f);
        }
    }

    void ReturnSprite()
    {
        animator.SetTrigger("doStop"); // 애니메이션이 멈추는 메서드
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("RedMelee"))
        {
            if (!isDamage)
            {
                //Bullet bullet = other.gameObject.GetComponent<Bullet>();
                
                    health -- ;
                    StartCoroutine(OnDamage());
                    OnHit();
                    Debug.Log("왼쪽에 있는 블루팀 병사가 공격을 받았습니다.");
                
            }
        }
    }

    IEnumerator OnDamage()
    {
        isDamage = true;
        // 피격 이벤트 생략
        yield return new WaitForSeconds(1f);
        isDamage = false;
        // 피격 이벤트에서 돌아오는거 생략
    }

    void Update()
    {
        // BS를 왼쪽으로 이동시키기
        MoveLeft();
    }

    void MoveLeft()
    {
        // 현재 속도를 왼쪽 방향으로 설정
        rb.velocity = new Vector2(-speed, rb.velocity.y);
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            if (!isAttacking)
            {
                isAttacking = true;
                attackCoroutine = StartCoroutine(AttackRoutine());
            }
        }
    }

    void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            StopAttack();  // 공격 중지
        }
    }

    IEnumerator AttackRoutine()
    {
        while (isAttacking)
        {
            AttackDa();
            yield return new WaitForSeconds(1f);
        }
    }

    void AttackDa()
    {
        animator.SetTrigger("doAttack");
    }

    void StopAttack()
    {
        if (attackCoroutine != null)
        {
            StopCoroutine(attackCoroutine);
            attackCoroutine = null;
        }
        isAttacking = false;
        animator.ResetTrigger("doAttack");
    }
}