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

public class GameManager : MonoBehaviour
{
	public static int[] levelArray = {1, 2, 3, 4, 5, 6, 7, 8};
	public static int currentLevelIndex = 0;

	public static Vector2 verticalNormalMod;
	public static Vector2 horizontalNormalMod;

	Dictionary<Collider2D, CueBehaviour> cuesByCollider = new Dictionary<Collider2D, CueBehaviour>();

	void Start()
	{
		GameObject[] cues = GameObject.FindGameObjectsWithTag("Cue");
		for (int i = 0; i < cues.Length; i++)
		{
			cuesByCollider.Add(cues[i].GetComponent<Collider2D>(), cues[i].gameObject.GetComponent<CueBehaviour>());
		}
	}

	void Update ()
	{
		if(Input.GetKeyDown(KeyCode.R)) SceneManager.LoadScene(levelArray[currentLevelIndex]);

		if(Input.GetKey(KeyCode.Mouse0))
		{
			Collider2D col = Physics2D.OverlapPoint((Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition));

			if(col != null && col.CompareTag("Cue"))
			{
				cuesByCollider[col].Push();
			}
		}

		if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) verticalNormalMod = Vector2.left;
		else if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) verticalNormalMod = Vector2.right;
		else verticalNormalMod = Vector2.zero;

		if(Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) horizontalNormalMod = Vector2.down;
		else if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) horizontalNormalMod = Vector2.up;
		else horizontalNormalMod = Vector2.zero;
	}

	void FixedUpdate ()
	{
		if(Input.GetKey(KeyCode.Mouse0))
		{
			Collider2D col = Physics2D.OverlapPoint((Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition));

			if(col != null && col.CompareTag("Cue"))
			{
				cuesByCollider[col].Push();
			}
		}
	}

	void OnTriggerStay2D(Collider2D col)
	{
		if(col.attachedRigidbody.velocity.magnitude <= 0.1f)
		{			
			if(currentLevelIndex + 1 > levelArray.Length) Application.Quit();
			else currentLevelIndex++;
			SceneManager.LoadScene(levelArray[currentLevelIndex]);
		}
	}
}