using UnityEngine;

public class Player : SingletonComponent<Player>
{
    Rigidbody2D rigid;
    SpriteRenderer sprite;
    Animator animator;
    Camera playerCamera;

    public Vector2 inputVec;
    public float speed;
    public LayerMask interactableLayer;

    private void Awake()
    {
        rigid = GetComponent<Rigidbody2D>();
        sprite = GetComponent<SpriteRenderer>();
        animator = GetComponent<Animator>();
        playerCamera = Camera.main;
    }

    private void Update()
    {
        Interact();
        InputMove();
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void LateUpdate()
    {
        MoveAnimation();
    }

    void InputMove()
    {
        inputVec.x = Input.GetAxisRaw("Horizontal");
        inputVec.y = Input.GetAxisRaw("Vertical");
    }

    private void Move()
    {
        Vector2 nextVec = inputVec.normalized * speed * Time.fixedDeltaTime;
        rigid.MovePosition(rigid.position + nextVec);
    }

    private void MoveAnimation()
    {
        animator.SetFloat("Speed", inputVec.magnitude);

        if (inputVec.x != 0)
            sprite.flipX = inputVec.x < 0;
    }

    private void Interact()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, interactableLayer);

            if (hit.collider != null)
            {

            }
        }
    }

    public void ChageClothes(int clothsNum)
    {
        if (animator == null)
        {
            Awake();
        }
        animator.SetInteger("Clothes", clothsNum);
    }
}
