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


public class PlayerMovements : MonoBehaviour {
    [SerializeField] private float speed = 5f;
    [SerializeField] private float jumpSpeed = 5f;
    private bool isLookingRight = true;
    private float horizontal;
    public bool hasBubble;

    [SerializeField] private bool IsOnGround;
    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] LayerMask groundLayer;
    [SerializeField] PlayerAnimation playerAnimation;
    [SerializeField] Animator bubble_animator;
    [SerializeField] GameManager gameManager;

    public event EventHandler OnForwardPressed; 
    public event EventHandler OnJumpPressed;

    private void Awake() {
        hasBubble = true;
    }

    private void Update() {

        horizontal = Input.GetAxis("Horizontal");

        if (horizontal != 0) {
            OnForwardPressed.Invoke(this, EventArgs.Empty);
        }
        else {
            playerAnimation.StopRunning();
        }

        if (CheckFlip()){
            Flip();
        };

        HandleJump();
    }

    private void FixedUpdate() {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    //Checks if the player is moving to the direction that sprite is not facing
    private bool CheckFlip() {
        if (isLookingRight && horizontal < 0f || !isLookingRight && horizontal > 0f) {
            return true;
        }

        return false;
    }

    // Flip the sprite vertically
    private void Flip() {
        isLookingRight = !isLookingRight;

        Vector3 localScale = transform.localScale;
        localScale.x *= -1f;
        transform.localScale = localScale;
    }

    //Checks the player is touching the ground
    private bool IsGrounded() {
        IsOnGround = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
        return IsOnGround;
    }

    private void HandleJump() {
        if (hasBubble && Input.GetKeyDown(KeyCode.Space)) {
            OnJumpPressed.Invoke(this, EventArgs.Empty);
            rb.velocity = new Vector3(rb.velocity.x, jumpSpeed);
        }
        else if (IsGrounded() && Input.GetKeyDown(KeyCode.Space)) {
            OnJumpPressed.Invoke(this, EventArgs.Empty);
            rb.velocity = new Vector3(rb.velocity.x, jumpSpeed);
        }
    }

    public void BurstBubble() {
        hasBubble = false;

        bubble_animator.SetTrigger("Pop");
        bubble_animator.gameObject.SetActive(false);
    }

    public void absorbBubble() {
        hasBubble = true;

        bubble_animator.gameObject.SetActive(true);
        gameManager.ChangeTheme();
    }
}