using UnityEngine;
using UnityEngine.UI;

public class CinematicBars : MonoBehaviour
{
	[Range(0,1)]
	public float size = 0.15f;

	public float time = 1.0f;

	RectTransform top, bottom;
	bool _shown;
	bool active;
	float fade;

	public bool shown {
		get { return _shown; }
		set {
			if (value != _shown) {
				_shown = value;
				active = true;
			}
		}
	}

    void Awake()
    {
		GameObject g = new GameObject("Top");
		g.transform.SetParent(transform, false);
		g.AddComponent<Image>().color = Color.black;
		top = g.GetComponent<RectTransform>();
		top.offsetMin = Vector2.zero;
		top.offsetMax = Vector2.zero;
		top.anchorMin = new Vector2(0, 1);
		top.anchorMax = new Vector2(1, 1);

		g = new GameObject("Bottom");
		g.transform.SetParent(transform, false);
		g.AddComponent<Image>().color = Color.black;
		bottom = g.GetComponent<RectTransform>();
		bottom.offsetMin = Vector2.zero;
		bottom.offsetMax = Vector2.zero;
		bottom.anchorMin = new Vector2(0, 0);
		bottom.anchorMax = new Vector2(1, 0);

		active = _shown = false;
		fade = 0;
	}

	void Update()
    {
		if (active) {
			float delta = UIWrangler.deltaTime / time;
			if (_shown) {
				fade += delta;
				if (fade >= 1) {
					fade = 1;
					active = false;
				}
			} else {
				fade -= delta;
				if (fade <= 0) {
					fade = 0;
					active = false;
				}
			}
		}

		float y = fade * size;
		top.anchorMin = new Vector2(0, 1-y);
		bottom.anchorMax = new Vector2(1, y);
	}
}
