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

/// <summary>
/// Displays a single notification
/// </summary>
public class NotificationWidget : BaseBehaviour
{

	[SerializeField]
	private Text notificationLabel;
	[SerializeField]
	private float fadeOutTime = 10;

	private CanvasGroup canvasGroup;
	private WidgetList parentWidgetList;

	private void Awake()
	{
		CheckIfSet(notificationLabel);

		GetComponentsWithNullCheck(ref canvasGroup);

		parentWidgetList = GetComponentInParent<WidgetList>();
	}

	public void Init(string notification)
	{
		notificationLabel.text = notification;
		StartCoroutine(_FadeOut());
	}

	private IEnumerator _FadeOut()
	{
		float timeLeft = fadeOutTime;

		while (timeLeft > 0)
		{
			timeLeft -= Time.deltaTime;
			canvasGroup.alpha = timeLeft / fadeOutTime;
			yield return null;
		}

		RemoveSelf();
	}

	private void RemoveSelf()
	{
		if (parentWidgetList != null)
			parentWidgetList.RemoveWidget(this);
	}

}
