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

public class Ball : MonoBehaviour {

	[SerializeField] float dir = 3f;
	float origin = 0f;
	int nextExpectedPlayer;

	[SerializeField]RotateCamera camera;

	// Use this for initialization
	void Start () {
		
		nextExpectedPlayer = dir>0 ? 0 : 1;
	}

	void Update () {
		transform.position = new Vector3 (transform.position.x + Time.deltaTime * dir, Mathf.Sin (3f * (Time.time - origin)) * 0.1f * Mathf.Abs(dir), 0f);
		//transform.position = new Vector3 (transform.position.x + Time.deltaTime * dir, 0, 0f);
	}
	/*
	void OnCollisionEnter2D(Collision2D c){
		if (c.gameObject.CompareTag ("Player")) {
			if (c.gameObject.GetComponent<PlayerController> ().player == nextExpectedPlayer) {
				dir = dir * -1f;
				int bla = nextExpectedPlayer == 0 ? 1 : -1;
				//origin = Time.time;

				Vector3 normal = c.gameObject.transform.position - transform.position;
				normal *= bla;
				Debug.Log ("normal: " + normal + " right: " + c.gameObject.transform.right + " angle: " + Vector2.Angle (normal, c.gameObject.transform.right));
				camera.Rotate (Vector2.Angle (normal, c.gameObject.transform.right),transform.position);
				nextExpectedPlayer = (nextExpectedPlayer + 1) % 2;
				//transform.localPosition += normal;
			}
		} else {
			camera.Rotate (-Camera.main.transform.eulerAngles.z * 2, transform.position);
		}



	}
	*/

	void OnCollisionEnter2D(Collision2D c){
		if (c.gameObject.CompareTag ("Player")) {
			if (c.gameObject.GetComponent<PlayerController> ().player == nextExpectedPlayer) {
				dir = dir * -1f;

				if (dir > 0)
					dir++;
				else
					dir--;
				
				int bla;
				float angle;
				Debug.Log (Camera.main.transform.eulerAngles.z);
				if (Camera.main.transform.eulerAngles.z > 180)
					angle = 360 - Camera.main.transform.eulerAngles.z;
				else
					angle = Camera.main.transform.eulerAngles.z;
				
				if (Camera.main.transform.eulerAngles.z > 310 && nextExpectedPlayer == 0) {
					Debug.Log ("Caso 1");
					bla = 1;
				}else if(nextExpectedPlayer == 0){
					Debug.Log ("Caso 2");
					bla = -1;
				}else if(Camera.main.transform.eulerAngles.z > 310 && nextExpectedPlayer != 0){	
					Debug.Log ("Caso 3");
					bla = 1;
				}else{
					Debug.Log ("Caso 4");
					bla = -1;
				}

				gameObject.GetComponent<Rigidbody2D> ().mass -= 0.01f;
				 
				//origin = Time.time;

				camera.Rotate (90 *bla  ,transform.position);
				nextExpectedPlayer = (nextExpectedPlayer + 1) % 2;
				//transform.localPosition += normal;
			}
		} else {
			camera.Rotate (-Camera.main.transform.eulerAngles.z * 2, transform.position);
		}



	}
}
