using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class ScrollableBackground : MonoBehavclops
{
    public Transform tileableImage;

    public float scrollSpeed = 0.3f;
    private float numTiles = 4;

    private List<Transform> tiles = new List<Transform>();

    private float topBound;
    private float bottomBound;
    private float tileHeight; 

    protected void Start()
    {
        //just spawn this prefab for the height
        Transform aTile = (Transform)GameObject.Instantiate(tileableImage);
        tileHeight = aTile.renderer.bounds.size.y - 2;
        GameObject.Destroy(aTile.gameObject);

        //set bounds based on height
        topBound = numTiles * tileHeight / 2f;
        bottomBound = -numTiles * tileHeight / 2f;

        //actually populate our list
        for (Vector3 v = new Vector3(transform.position.x, topBound, transform.position.z); v.y >= bottomBound; v.y -= tileHeight)
        {
            Transform t = (Transform)GameObject.Instantiate(tileableImage, v, Quaternion.identity);
            t.parent = transform;
            //put it in the back
            t.GetComponent<SpriteRenderer>().sortingOrder = -100;
            tiles.Add(t);
        }
    }

    protected void Update()
    {
        foreach(var tile in tiles)
        {
            tile.Translate(new Vector3(0, -scrollSpeed*Time.deltaTime, 0));
            if(tile.position.y+tileHeight<bottomBound)
            {
                tile.position = new Vector3(transform.position.x, topBound, transform.position.z);
            }
        }
    }

}
