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

public class MarbleMovement : MonoBehaviour
{
    public float speed;
    public float jumpForce;

    private Rigidbody rb;
    private Vector3 movement;
    private float verticalMove;
    private float horizontalMove;
    public bool isOnTheGround;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }
    
    void FixedUpdate()
    {
        if (GameManager.instance.inProgress)
        {
            Roll();
            Jump();
        }
    }

    void Roll()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal");
        verticalMove = Input.GetAxisRaw("Vertical");

        if (horizontalMove != 0f || verticalMove != 0f)
        {
            speed += Time.deltaTime * 3f;
        }
        else if (horizontalMove == 0f && verticalMove == 0f)
        {
            speed -= Time.deltaTime * 30f;
            if (speed < 0.1f)
            {
                speed = 0.1f;
            }
        }
        Vector3 direction;
        movement = new Vector3(horizontalMove, 0, verticalMove);
        direction = Camera.main.transform.TransformDirection(movement);
        direction.y = 0;
        direction.Normalize();
        speed = Mathf.Clamp(speed, 0.1f, 10.0f);
        rb.AddForce(speed * direction);
    }

    private void Jump()
    {
        if (isOnTheGround && Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(Vector3.up * jumpForce);
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "CanJumpOn")
        {
            isOnTheGround = true;
        }

        if (collision.gameObject.tag == "Arrival")
        {
            Debug.Log("You win.Congratz. Wohoo.");
            Time.timeScale = 0;
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.tag == "CanJumpOn")
        {
            isOnTheGround = !isOnTheGround;
        }
    }
}
