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

public class Player : MonoBehaviour
{
    public float speed = 1.0f;
    public float limit = 0.48f;
    public float weight = 1.0f;
    public float jumpDuration = 0.5f;
    public float jumpForce = 1.0f;

    public AudioSource jumpnoise;
    public AudioSource thudnoise;

    Rigidbody rbPlane;
    Transform cylinder;
    ParticleSystem splash;
    CubeSpawn gameOver;

    float jumpTime;

    // Start is called before the first frame update
    void Start()
    {
        rbPlane = transform.parent.gameObject.GetComponent<Rigidbody>();
        cylinder = transform.GetChild(0);
        splash = transform.GetChild(1).GetComponent<ParticleSystem>();
        gameOver = (CubeSpawn)FindObjectOfType(typeof(CubeSpawn));
    }

    // Update is called once per frame
    void Update()
    {
        if (gameOver.IsGameOver()) return;

        Vector3 newPos = transform.localPosition;
        newPos.x += Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        newPos.z += Input.GetAxis("Vertical") * speed * Time.deltaTime;

        if (newPos.x >= limit) newPos.x = limit;
        if (newPos.z >= limit) newPos.z = limit;

        if (newPos.x <= -limit) newPos.x = -limit;
        if (newPos.z <= -limit) newPos.z = -limit;

        transform.localPosition = newPos;

        if (jumpTime <= 0 && Input.GetKeyDown("space") || Input.GetKeyDown("joystick button 0"))
        {
            jumpnoise.Play();
            jumpTime = 1.0f;
        }
    }

    void FixedUpdate()
    {
        rbPlane.AddForceAtPosition(weight*-transform.up, transform.position);

        Vector3 newCylinderPos = cylinder.localPosition;
        newCylinderPos.y -= 0.6f;

        if (jumpTime > 0)
        {
            jumpTime -= Time.deltaTime / jumpDuration;
            float altitude = 1.0f - (2 * jumpTime - 1) * (2 * jumpTime - 1);
            newCylinderPos.y = altitude;
            
            if (jumpTime < 0) // just landed
            {
                rbPlane.AddForceAtPosition(200*jumpForce*weight*-transform.up, transform.position);
                splash.Play();
                thudnoise.Play();
            }

        }
        else
        {
            jumpTime = 0.0f;
            newCylinderPos.y = 0.0f;
        }

        newCylinderPos.y += 0.6f;
        cylinder.localPosition = newCylinderPos;
    }
}
