using UnityEngine;
using System.Collections;

public class BackgroundController : MonoBehaviour {

    public float transistionSpeed = 1f;
    public float waitTime = 10f;

    private Material mat;

    private float lastTransition = 0.0f;
    private bool inverseDirection = false;


	// Use this for initialization
	void Start () {
        mat  = GetComponent<Renderer>().material;
    }
	
	// Update is called once per frame
	void FixedUpdate () {

        if (Time.time - lastTransition >= waitTime) {
            lastTransition = Time.time;
            StartCoroutine(transition(transistionSpeed));
        }

	}

    private IEnumerator transition(float time) {

        float transitionStart = -1;
        float transitionEnd = 1;
        
        if (inverseDirection) {           
            mat.SetFloat("_InvertMap", 1);
        }else {
            mat.SetFloat("_InvertMap", 0);
        }

        float elapsedTime = 0;
        float transitionFrac = transitionStart;

        while ((elapsedTime/ time) <=1) {
            transitionFrac = Mathf.Lerp(transitionStart, transitionEnd, (elapsedTime / time));
            

            transitionFrac = (inverseDirection)? transitionFrac : -transitionFrac;

            mat.SetFloat("_TimeNode", transitionFrac);

            elapsedTime += Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }

        if (inverseDirection) {
            mat.SetFloat("_TimeNode", 1);
        } else {
            mat.SetFloat("_TimeNode", -1);
        }
            
        inverseDirection = !inverseDirection;
    }


}
