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

public class PlayerController : MonoBehaviour {
    [SerializeField]
    private float walkSpeed = 10;
	private float speed = 0;
	public bool isGorunded = false;
    [SerializeField]
    private float jumpForce = 10;
	private SpriteRenderer rd;
    private Animator anim;
    private Rigidbody2D player;
	private bool movedInThisFrame = false;
	public bool playable = true;

//	private float timer = 0;
//	private const float maxTime = .5f;
//	private bool 

	void Start () {

        anim = GetComponent<Animator>();
        player = GetComponent<Rigidbody2D>();
		rd = GetComponent <SpriteRenderer> ();

	}
	
	void Update () {
		movedInThisFrame = false;
		if (playable) {

				speed = walkSpeed;
			if (!isGorunded)
				speed = walkSpeed / 3;

			if (Input.GetKey (KeyCode.D)) {
				movedInThisFrame = true;
				transform.position += (new Vector3 (speed * Time.deltaTime, 0, 0));
				rd.flipX = false;
			} else if (Input.GetKey (KeyCode.A)) {
				movedInThisFrame = true;
				transform.position -= (new Vector3 (speed * Time.deltaTime, 0, 0));
				rd.flipX = true;
			}

			if (isGorunded) {
				if (Input.GetKeyDown (KeyCode.Space)) {
					anim.SetInteger ("State", 2);
					player.AddForce (new Vector2 (0, jumpForce));

					isGorunded = false;
				} else {
					if (movedInThisFrame) {
						anim.SetInteger ("State", 1);
					} else {
						anim.SetInteger ("State", 0);
					}
				}
			}
		} else {
			Camera.main.transform.SetParent (null);
			player.AddForce (new Vector2(-19000, 19000));
			player.AddTorque(190000);
			SceneManager.LoadScene ("Level_1");
		}



	}

	void OnCollisionEnter2D(Collision2D coll){
		if (coll.gameObject.tag.Equals ("Floor"))
			isGorunded = true;
			movedInThisFrame = true;
	}

}
