using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{

    [SerializeField] public float speed = 1;
    [SerializeField] public float rotationSpeed = 1;

    public float startRotationSpeed;

    [SerializeField] public Vector3 resetPos = Vector2.zero;

    private Vector2 input;

    public byte lifes = 3;

    private Rigidbody2D m_Rigidbody;
    [SerializeField] GameObject painParticle;

    GameObject keyParent;

    TextMeshProUGUI lifesCounter;

    [SerializeField] float invincibleTime = 0.5f;
    float currentTime = 0f;

    AudioSource hurtSound;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startRotationSpeed = rotationSpeed;
        m_Rigidbody = GetComponent<Rigidbody2D>();
        keyParent = GameObject.FindGameObjectWithTag("KeysParent");
        lifesCounter = GameObject.Find("lifeCounter").GetComponent<TextMeshProUGUI>();
        hurtSound = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        currentTime += Time.deltaTime;

        input = new Vector2(Input.GetAxis("Horizontal") * speed, Input.GetAxis("Vertical") * speed);

        if (input == Vector2.zero)
        {
            m_Rigidbody.linearDamping = 1000f;
        }
        else
        {
            m_Rigidbody.linearDamping = 1f;
        }
    }

    private void FixedUpdate()
    {
        m_Rigidbody.rotation += rotationSpeed;

        m_Rigidbody.linearVelocity = input;

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (currentTime < invincibleTime)
        {
            transform.position -= new Vector3(input.x * 0.1f, input.y * 0.1f, 0);
            return;
        }

        PlayHurtSound();

        currentTime = 0f;

        lifes -= 1;

        m_Rigidbody.rotation -= rotationSpeed * 25;

        transform.position -= new Vector3(input.x * 0.1f, input.y * 0.1f, 0);

        Vector3 point = collision.contacts[0].point;

        Instantiate(painParticle, point, Quaternion.identity);

        if (lifes <= 0)
        {
            lifes = 3;
            ResetStuff();
            rotationSpeed = startRotationSpeed;
            Debug.Log("keep urself safe");


        }
        UpdateLifeText();
    }

    public void UpdateLifeText()
    {
        lifesCounter.text = "Health: " + lifes;
    }

    public void ResetStuff()
    {
        transform.position = resetPos;
        m_Rigidbody.rotation = 0f;

        foreach (Transform key in keyParent.transform)
        {
            ObjectDeleter keyScript = key.GetComponent<ObjectDeleter>();
            keyScript.Reset();
        }
    }

    public void PlayHurtSound()
    {
        hurtSound.pitch = Random.Range(0.95f, 1.05f);
        hurtSound.Play();
    }
}
