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

using UnityEngine.SceneManagement;
using UnityEngine.Tilemaps;

public class CatcherS : MonoBehaviour {

	public const float moveForce = 30f;
	public const float maxSpeed = 3f;
	public const float jumpForce = 300f;

	public bool grounded;
	public bool catched = false;
	private bool facingRight = true;
	public bool jump = false;

	public Rigidbody2D rb2d;
	public Camera myCamera;
	public StateHandlerS stateHandler;
	public BallS ball;

	private Animator anim;

	public string catchedColor;

	void Awake () {
		rb2d = GetComponent<Rigidbody2D>();
		anim = GetComponent<Animator> ();
		PhysicsMaterial2D frictionless = new PhysicsMaterial2D ();
		frictionless.friction = 0;
		rb2d.sharedMaterial = frictionless;
	}

	void Update () {
		if (Input.GetKeyDown(KeyCode.W) && grounded) {
			jump = true;
		}
	}

	void FixedUpdate() {
		if (stateHandler.currentState == StateHandlerS.DURING_LEVEL) {
			float h = Input.GetAxis ("Horizontal");
			if (h * rb2d.velocity.x < 0) {
				rb2d.velocity = new Vector2 (0, rb2d.velocity.y);
			}
			if (Mathf.Abs (h * rb2d.velocity.x) < maxSpeed) {
				rb2d.AddForce (Vector2.right * h * moveForce);
			}
			if (Mathf.Abs (rb2d.velocity.x) > maxSpeed) {
				rb2d.velocity = new Vector2 (Mathf.Sign (rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);
			}
			if (h == 0) {
				rb2d.velocity = new Vector2 (0, rb2d.velocity.y);
			}

			if (rb2d.velocity.x > 0 && !facingRight) {
				flip ();
			} else if (rb2d.velocity.x < 0 && facingRight) {
				flip ();
			}

			if (jump) {
				rb2d.AddForce (new Vector2 (0f, jumpForce));
				jump = false;
			}

			anim.SetBool ("isWalking", Mathf.Abs (rb2d.velocity.x) > 0);
			anim.SetBool ("catched", catched);
		}
	}

	public void flip() {
		if (catched) {
			ball.transform.parent = null;
		}
		facingRight = !facingRight;
		Vector3 theScale = transform.localScale;
		theScale.x *= -1;
		transform.localScale = theScale;
		if (catched) {
			ball.transform.parent = this.gameObject.transform;
		}
	}

}
