using UnityEngine;
using System.Collections;
using System;

public class Goal : MonoBehaviour {
	
	[SerializeField] private int keysRequiredToOpen = 0;
	[SerializeField] private Material lockedMaterial;
	[SerializeField] private Material unlockedMaterial;
	
	private bool isUnlocked;
	
	private void Start() {
		Debug.Log(Application.levelCount);
		if (keysRequiredToOpen == 0) {
			Debug.Log("Goal requires no keys. Unlocking from level start");
			renderer.material = unlockedMaterial;
			isUnlocked = true;
			return;
		}
		UnityEngine.Object[] keysInScene = FindObjectsOfType(typeof(Key));
		if (keysInScene != null && keysInScene.Length < keysRequiredToOpen) {
			Debug.LogError("A goal doesn't have enough keys to open it. The maximum amount of keys found in the level (" + keysInScene + ") will be used instead");
			keysRequiredToOpen = keysInScene.Length;
		}
			
		Key.ListenToTargetCount(keysRequiredToOpen, OnKeysCollected);
		renderer.material = lockedMaterial;
		isUnlocked = false;
	}
	
	private void OnKeysCollected() {
		Debug.Log("Keys collected for goal!");
		renderer.material = unlockedMaterial;
		isUnlocked = true;
	}
	
	private void OnTriggerEnter(Collider collider) {
		if (collider.name.StartsWith("Player")) {
			if (isUnlocked) {
				Debug.Log("Level clear!");
				int nextLevel = Application.loadedLevel+1;
				if (nextLevel >= Application.levelCount) {
					Application.LoadLevel("Level1");
				}
				else {
					Application.LoadLevel(nextLevel);
				}
			}
			else {
				Debug.Log("Player needs more keys");
			}
		}
	}
}
