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

public class Player : MonoBehaviour
{
    [SerializeField]private Transform body;
    [field:SerializeField]public Vector2 Velocity {get; private set;}
    [SerializeField]private float gravity=1;
    [SerializeField]private float jumpForce= 5;
    [SerializeField]private float forwardSpeed=  0.1f;
    [SerializeField]private float jumpCooldown = 0.5f;
    [SerializeField]private float radius = 0.5f;

    [Header("Sprites")]
    public Sprite normalFace;
    public Sprite sadFace;

    public bool isReadyToJump { get{ return jumpTimer >= jumpCooldown;}}


    private float jumpTimer= 0;

    private Vector3 startPos;
    public bool isAlive{get;private set;}


    private SpriteRenderer spriteRenderer;

    void Start(){
        spriteRenderer = GetComponent<SpriteRenderer>();
        isAlive = true;
        spriteRenderer.sprite =normalFace;

        startPos = body.position;
        Velocity = new Vector2(forwardSpeed,0);

        CameraFollower.Target= body;
    }

    void FixedUpdate()
    {
        if(!isAlive){ return; }
        HandleDeath();

        if(Input.GetKey(KeyCode.Space)){
            Jump();
        }
        HandleJump();

        //Gravity
        Velocity -= new Vector2(0, gravity);

        body.Translate(Velocity);

        CameraFollower.UpdateFrame();
    }

    void HandleDeath(){
        Collider2D col = Physics2D.OverlapCircle(body.position, radius);
        if(col == null){ return;}
        if(col.tag == "Death"){
            Debug.Log("Im dead bro");
            isAlive = false;
            spriteRenderer.sprite = sadFace;

            GameUI.ShowDeath();
        }
    }

    void HandleJump(){
        if(jumpTimer < jumpCooldown){
            jumpTimer += Time.deltaTime;
        }
    }


    public void Jump(){
        if(!isReadyToJump){ return; }
        jumpTimer =0;
        Velocity = new Vector2(Velocity.x, jumpForce);
    }


    void OnValidate(){
        if(body == null){
            body = transform;
        }
    }


    void OnTriggerEnter2D(Collider2D other){
        Debug.Log(other.name);
    }

    void OnGizmos(){
        Gizmos.DrawWireSphere(body.position, radius);
    }
}
