using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;

public class CharacterMovement : NetworkBehaviour
{
    private CharacterController controller;
    private Vector3 playerVelocity;
    public bool groundedPlayer;
    public float playerSpeed = 2.0f;
    public float jumpHeight = 1.0f;
    public float gravityValue = -9.81f;

    public float kickSpeed = 0.25f;
    bool kicking;

    Rigidbody rb;

    private void Start()
    {
        controller = gameObject.GetComponent<CharacterController>();
        rb = this.GetComponent<Rigidbody>();
    }

    void Update()
    {

        if (!IsOwner) return;

        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        this.transform.position += 
            move * Time.deltaTime * playerSpeed;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (!kicking) StartCoroutine(Kick());
        }

        /*
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        controller.Move(move * Time.deltaTime * playerSpeed);

        if (move != Vector3.zero)
        {
            gameObject.transform.forward = move;
        }

        // Changes the height position of the player..
        if (Input.GetButtonDown("Jump") && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);

        */
    }

    IEnumerator Kick()
    {
        kicking = true;
        //rb.isKinematic = true;
        for (float i = 0; i < kickSpeed; i+= Time.deltaTime)
        {
            var value = Mathf.PingPong(i / kickSpeed, 360);

            var rotAmount =
                i / kickSpeed * 360;

            var rotation = new Vector3(0, 0, rotAmount);        

            this.transform.eulerAngles = rotation;

            yield return
                 null;
        }

        this.transform.eulerAngles = new Vector3(0, 0, 360);

        kicking = false;
        //rb.isKinematic = false;
    }
}
