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

public class PlayerController : MonoBehaviour {

	[SerializeField]
	public int player;	
	private KeyCode up;
	private KeyCode down;
	private KeyCode powerUp;
	private int score;
	Rigidbody2D aux;
	Bounce bounce;

	float energyCounter, charge;
	bool energyAvailable;

	[SerializeField]
	GameObject[] ballList;

	[SerializeField]
	bool AI;

	[SerializeField]
	float objectiveY;

	// Use this for initialization
	void Start () {
		if (player == 0) {
			up = KeyCode.UpArrow;
			down = KeyCode.DownArrow;
			powerUp = KeyCode.RightArrow;
		} else {
			up = KeyCode.W;
			down = KeyCode.S;
			powerUp = KeyCode.D;
		}
		score = 0;
		bounce = GetComponent<Bounce> ();
		energyAvailable = false;
		energyCounter = 0;

	}
	
	// Update is called once per frame
	void Update () {
	
		if (AI) {
			float parcial, min = 9999f;

			ballList = GameObject.FindGameObjectsWithTag ("Ball");

			foreach (GameObject go in ballList) {
				go.GetComponent<PhysicBall> ().isAI = true;
				aux = go.GetComponent<Rigidbody2D> ();
				if (aux.velocity.x < 0) {
					if (-(go.transform.position.x - transform.position.x) / aux.velocity.x < min) {
						min = -(go.transform.position.x - transform.position.x) / aux.velocity.x;
						objectiveY = go.transform.position.y;
					}
				}
			}

			if (objectiveY < transform.position.y && transform.localPosition.y > -3.5f)
				transform.localPosition -= Vector3.up * 10f * Time.deltaTime;
			if (objectiveY > transform.position.y && transform.localPosition.y < 3.5f)
				transform.localPosition += Vector3.up * 10f * Time.deltaTime;

				
				
		} 
	

		if(energyAvailable && Input.GetKeyDown(powerUp)){
			bounce.SetCharge(2f);
			energyAvailable = false;
			energyCounter = 0;
		}

		
		if(Input.GetKey(down) && transform.localPosition.y > -3.5f)
			transform.localPosition -= Vector3.up * 10f * Time.deltaTime;
		if(Input.GetKey(up) && transform.localPosition.y < 3.5f)
			transform.localPosition += Vector3.up * 10f * Time.deltaTime;
	}

	public void BallIn(){
		bounce.IncreaseBounce (0f);
	}


	void OnCollisionEnter2D(){
		if (energyCounter > 5 && !energyAvailable) {
			energyAvailable = true;
		} else {
			energyCounter++;

		}
	}



}
