using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Linq;
public class UIScreen : MonoBehaviour,IUIScreen {

	public static List<IUIScreen> History;
	public static List<IUIScreen> Screens;
	private RectTransform myRect;

	public bool IsShown = false;

	// Use this for initialization
	public virtual void Awake() {
		myRect = GetComponent<RectTransform>();
		if(UIScreen.Screens == null) {
			UIScreen.Screens = new List<IUIScreen>();
		}
		UIScreen.Screens.Add(this);

		
		if(UIScreen.History == null) {
			UIScreen.History = new List<IUIScreen>();
		}

		
	}
	public virtual void OnEnable () {

	}
	
	// Update is called once per frame
	public virtual void OnDisable () {
		//UIScreen.Screens.Remove(this);
		
	}

	public virtual void Show(bool additional = false) {
		if(!additional) {
			HideAllOthers();
		}

		for(int i = 0; i < myRect.childCount;i++) {
			myRect.GetChild(i).gameObject.SetActive(true);
		}
		
		UIScreen.History.Add(this);
		setFirst();
		IsShown = true;
	}

	void setFirst() {
		StartCoroutine(setFirstRoutine());
	}

	IEnumerator setFirstRoutine() {
		yield return new WaitForEndOfFrame();

		List<Button> b = GetComponentsInChildren<Button>().ToList();
		List<Button> activeButtons = b.Where(but=>but.interactable == true).ToList();

		if(activeButtons.Count > 0) {
			GameObject first = activeButtons[0].gameObject;
			EventSystem.current.SetSelectedGameObject(first);
			yield return new WaitForEndOfFrame();
		} else {
			//Debug.LogWarning("No UI-Element to highlight found in "+gameObject.name+".");
		}
	}

	public virtual void HideAllOthers() {

		
		foreach(UIScreen ui in UIScreen.Screens) {
			if(!ui.GetInstanceID().Equals(this.GetInstanceID())) {
				ui.Hide();
			}
		}
	}

	public static void HideAll() {
		foreach(UIScreen ui in UIScreen.Screens) {
			ui.Hide();
		}
	}

	public virtual void Hide() {
		for(int i = 0; i < myRect.childCount;i++) {
			myRect.GetChild(i).gameObject.SetActive(false);
		}
		IsShown = false;
	}


	public void OnCancel(object sender, EventArgs<bool> e) {

	}

	public virtual void ButtonBack() {
		UIScreen.History.RemoveAt(UIScreen.History.Count-1);
		UIScreen.History[UIScreen.History.Count-1].Show();
	}

	public static IUIScreen GetScreen<T> () {
		return UIScreen.Screens.Find(s=>s.GetType().Equals(typeof(T)));
	}
}
