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

public class PlayerScript : MonoBehaviour
{

    public KeyCode[] keys;
    /*
     * order: left right jump
     */

    float jumptime;
    bool jumping;
    float jumpmoved;
    float lastmovevector;

    bool freefall;
    float touchtime;

    void Awake()
    {
        touchtime = Time.time;
        GetComponent<Rigidbody2D>().gravityScale = 1;
    }

    // Update is called once per frame
    void Update()
    {
        float dir = -1;
        bool getkey = false;
        if (Input.GetKey(keys[0]))
        {
            getkey = true;
            dir = -1;
        }
        if (Input.GetKey(keys[1]))
        {
            getkey = true;
            dir = 1;
        }
        if (getkey) { 
            if (!jumping && !freefall)
            {
                GetComponent<Rigidbody2D>().MovePosition(transform.position + Vector3.right *dir * 0.05f);
                lastmovevector = Mathf.MoveTowards(lastmovevector, dir, 0.1f);
            }
            else if (!freefall)
            {
                lastmovevector += dir*0.05f;
            }
            else if (freefall)
            {
                GetComponent<Rigidbody2D>().AddForce(Vector3.right * dir * 1f);
            }
        }
        else
        {
            lastmovevector = Mathf.MoveTowards(lastmovevector, 0, 0.5f);
        }

        if (Input.GetKeyDown(keys[2]) && !jumping && !freefall)
        {
            jumptime = Time.time;
            jumping = true;
            jumpmoved = 0;
            GetComponent<Rigidbody2D>().gravityScale = 0;
            //GetComponent<Rigidbody2D>().velocity = new Vector3(lastmovevector,0,0);
        }

        if (Input.GetKeyUp(keys[2]) && !freefall)
        {
            CancelJump();
        }

    }
    void CancelJump()
    {
        jumping = false;
        GetComponent<Rigidbody2D>().gravityScale = 1;
        freefall = true;
        GetComponent<Rigidbody2D>().velocity = Vector3.right * lastmovevector*0.25f;
    }
    private void FixedUpdate()
    {
        if (!jumping && Time.time-touchtime > 0.3f && !freefall)
        {
            freefall = true;
            GetComponent<Rigidbody2D>().velocity = Vector3.right * lastmovevector * 0.25f;
            GetComponent<Rigidbody2D>().gravityScale = 1;
        }
        if (jumping)
        {
            if (Time.time - jumptime > 0.5f)
            {
                CancelJump();
            }
            else
            {
                if (jumpmoved < 20) { 
                    float mmt = 0.2f;
                    GetComponent<Rigidbody2D>().MovePosition(transform.position + Vector3.up*mmt/(1+jumpmoved*2) +
                        lastmovevector*Vector3.right*0.01f);
                    jumpmoved += mmt;
                }
            }
        }
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        
        touchtime = Time.time;
        freefall = false;
    }

}


