using UnityEngine;
using System.Collections;

public class MoveBackground : MonoBehaviour {

    public GameObject spawnBackground;

    private BackgroundManager backgroundManager;

    private Renderer renderer;
    private Material currentMaterial;

    private Vector3 spawnPoint;
    public bool isFirst;
    private bool hasSpawned;

    private float moveSpeed = 2;

    private Color currentColour;

	// Use this for initialization
	void Start ()
    {
        if (!isFirst)
        {
            hasSpawned = false;
        }
        else
        {
            hasSpawned = true;
        }
        spawnPoint = new Vector3(0, -196.65f, -984.81f);

        backgroundManager = transform.parent.GetComponent<BackgroundManager>();

        renderer = GetComponent<Renderer>();
    }
	
	// Update is called once per frame
	void Update ()
    {
        float newY = transform.position.y + (Time.deltaTime * moveSpeed);
        float newZ = transform.position.z + ((Time.deltaTime * moveSpeed) * 5.6f);
        transform.position = new Vector3(0, newY, newZ);

        if (transform.position.y >= -23 && !hasSpawned)
        {
            GameObject newBackground = Instantiate(spawnBackground);
            newBackground.transform.parent = transform.parent;
            newBackground.transform.position = spawnPoint;
            hasSpawned = true;
        }

        if (transform.position.y >= 150)
        {
            Destroy(gameObject);
        }

        currentColour = backgroundManager.currentColour;

        float alpha = backgroundManager.newAlpha;

        renderer.material.color = new Color(currentColour.r * alpha, currentColour.g * alpha, currentColour.b * alpha);
	}
}
