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

public class PlayerControl : MonoBehaviour
{
    private Vector3 moveX, moveY;
    private Vector3 rotationX, rotationY;
    private Vector3 moveDirection, rotCam, rotPlayer;
    private Rigidbody rb;
    private float speed, rotationSensitive;
    public Camera cam;
    public float fallDownFactor;
    public float walkFactor, runFactor;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        walkFactor = 3.3f;
        runFactor = 12.3f;
        rotationSensitive = 2f;
    }

    // Update is called once per frame
    void Update()
    {
        MoveControl();
        RotationControl();
        if (rb.velocity.y < 0)
        {
            rb.velocity += Vector3.up * Physics.gravity.y * fallDownFactor * Time.fixedDeltaTime;
        }
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveDirection);
        rb.MoveRotation(rb.rotation * Quaternion.Euler(rotPlayer));
        cam.transform.Rotate(rotCam);
    }

    void MoveControl()
    {
        if (Input.GetAxis("Horizontal") > 0.3f)
        {
            moveX = transform.right;
        }
        else if (Input.GetAxis("Horizontal") < -0.3f)
        {
            moveX = -transform.right;
        }
        else
            moveX = Vector3.zero;

        if (Input.GetAxis("Vertical") > 0.3f)
        {
            PlayerState.walkHeartBeat(walkFactor);
            moveY = transform.forward;
            speed = 80;
        }
        else if (Input.GetAxis("Vertical") < -0.3f)
        {
            PlayerState.walkHeartBeat(walkFactor);
            moveY = -transform.forward;
            speed = 80;
        }
        else if (Input.GetKey("2"))
        {
            PlayerState.walkHeartBeat(runFactor);
            moveY = transform.forward;
            speed = 200;
        }
        else
        {
            PlayerState.walkHeartBeat(0f);
            moveY = Vector3.zero;
        }            
        moveDirection = (moveX + moveY) * Time.fixedDeltaTime * speed;
        //moveDirection = moveY * Time.fixedDeltaTime * speed;
    }

    void RotationControl()
    {
        float rotY = Input.GetAxisRaw("Mouse X");
        float rotX = Input.GetAxisRaw("Mouse Y");
        rotCam = new Vector3(-rotX, 0f, 0f) * rotationSensitive;
        rotPlayer = new Vector3(0, rotY, 0f) * rotationSensitive;
    }
}
