using System;
using Data;
using UnityEngine;

public class Pawn : MonoBehaviour
{
    public Animator Animator => animator;
    
    [SerializeField] private UnitData unitData;
    [SerializeField] private SpriteRenderer spriteRenderer;
    [SerializeField] private Animator animator;

    protected float MaxHP;
    protected float CurrentHP;
    protected bool IsDead;
    
    private Vector2 _moveInput;

    private void Awake()
    {
        MaxHP = unitData.MaxHP;
        CurrentHP = MaxHP;
    }

    public void TakeDamage(float damage)
    {
        //animator.Play("HURT");
        CurrentHP -= damage;
        CheckDeath();
    }
    
    public virtual void HandleIdle()
    {
        animator.Play("Idle");
    }
    
    public virtual void HandleMove(Vector2 input)
    {
        _moveInput = input;
        animator.Play(input.magnitude > 0 ? "Walk" : "Idle");
        
        if (_moveInput.magnitude > 0)
            transform.localScale = new Vector3(_moveInput.x > 0 ? 1 : -1, 1, 1);
    }

    public virtual float HandleAttack(string attackName)
    {
        animator.Play(attackName);
        animator.Update(0f);
        var state = animator.GetCurrentAnimatorStateInfo(0);
        return state.length * state.speed;
    }
    
    private void FixedUpdate()
    {
        transform.Translate(_moveInput * unitData.MoveSpeed);
    }

    private void CheckDeath()
    {
        if (CurrentHP <= 0)
        {
            //animator.Play("Death");
            IsDead = true;
            Destroy(gameObject);
        }
    }
}
