using UnityEngine;
using System.Collections;
using System;

public class ButtonOpenGameObject : MonoBehaviour
{
	public tk2dSprite faderSprite;

	//Openning object
	public GameObject gameObjectToOpen;
	public bool shouldToogle = false;

	//Closing object
	public bool shouldCloseSelf = false;
	public GameObject ownObjectToClose;
	
	void Start () 
	{
		GetComponent<GenericButton>().releaseHandler += new ReleaseEventHandler(OpenObject);
	}
	
	void OpenObject(object sender, EventArgs e) 
	{
		StartCoroutine(FadeTransition());
	}

	IEnumerator FadeTransition()
	{
		faderSprite.gameObject.SetActive(true);
		float fadeTime = 0.5f;
		float lastTime = Time.time;

		while (Time.time - lastTime < fadeTime)
		{
			faderSprite.color = new Color(1, 1, 1, (Time.time - lastTime) / fadeTime);
			yield return new WaitForEndOfFrame();
		}

		while (Time.time - lastTime < fadeTime)
		{
			faderSprite.color = new Color(1, 1, 1, 1 - ((Time.time - lastTime) / fadeTime));
			yield return new WaitForEndOfFrame();
		}

		if (shouldToogle)
			gameObjectToOpen.SetActive(gameObjectToOpen.activeSelf);
		else 
			gameObjectToOpen.SetActive(true);

		faderSprite.gameObject.SetActive(false);

		if (shouldCloseSelf)
			ownObjectToClose.SetActive(false);
	}
	
	void Update () 
	{
	}
}
