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

public class Player : MonoBehaviour
{
    private Rigidbody2D rb;
    private SpriteRenderer playerSprite;
    private float movement = 10f;
    private float speed = 10f;
    private bool isGrounded;
    private float jumpSpeed = 1000f;
    private Animator playerAnimator;
    public GameObject mainCamera;
    public GameObject box;
    public GameObject level1Dialog;
    public bool facingright;

    public AudioSource walkSound;
    public AudioSource jumpSound;


    public GameObject nextLevel;
    public GameObject nextLevelPanel;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        playerAnimator = GetComponent<Animator>();
        playerSprite = GetComponent<SpriteRenderer>();
        isGrounded = true;
        SceneManager.LoadScene("Progress", LoadSceneMode.Additive);
    }

    // Update is called once per frame

    private void OnCollisionEnter2D(Collision2D other) 
    {
        if (other.gameObject.tag=="Ground")
        {
            isGrounded=true;
        }
        else
        {
            isGrounded=false;
        }

        if (other.gameObject.tag=="Trap")
        {
            SceneManager.LoadScene("Level1CutScene");
            print("youlose");
        }
    }
    void Update()
    {
        
        movement = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2( movement * speed, rb.velocity.y);

        Flip(movement);

        if (Input.GetKeyDown(KeyCode.Space) && isGrounded==true)
        {
            rb.AddForce(transform.up * jumpSpeed);
            isGrounded=false;
        }


        // if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.LeftArrow))
        // {
        //     walkSound.Play();
        // }
    }

    private void OnTriggerEnter2D(Collider2D other) 
    {
        if (other.gameObject.name=="Box passed Collider")
        {
            box.SetActive(true);
            level1Dialog.SetActive(true);
            SceneManager.LoadScene("Level1CutScene");
        }

        if (other.gameObject.name=="EndGame")
        {
            Destroy(Camera.main);
        }

        if (other.gameObject.name=="NextLevel")
        {
            nextLevelPanel.SetActive(true);
            Time.timeScale = 0;
        }
    }

    private void Flip(float movement)
    {
        if (movement < 0 && !facingright || movement > 0 && facingright)
        {   
            facingright = !facingright;
            playerSprite.flipX = !playerSprite.flipX;
        }
    }
}
