using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParallaxController : MonoBehaviour
{
    public float horizontalBound;
    public float[] layerHorizontalSlack;
    ParallaxLayer[] parallaxLayers;


    // Start is called before the first frame update
    void Awake()
    {
        if (this.layerHorizontalSlack.Length != transform.childCount)
        {
            throw new System.Exception("ParallaxController must have equal amount slacks as children");
        }

        this.parallaxLayers = new ParallaxLayer[transform.childCount];
        for (int i = 0; i < this.parallaxLayers.Length; i++)
        {
            this.parallaxLayers[i] = new ParallaxLayer(transform.GetChild(i), this.horizontalBound, this.layerHorizontalSlack[i]);
        }
        
    }

    // Update is called once per frame
    void Update()
    {
        foreach (ParallaxLayer layer in this.parallaxLayers)
        {
            layer.MoveLayer(this.GetComponent<Camera>().transform.position);
        }
    }

    private class ParallaxLayer
    {
        Vector3 originalPosition;
        Transform tr;
        float bound;
        float slack;

        public ParallaxLayer(Transform transform, float bound, float slack)
        {
            this.originalPosition = transform.localPosition;
            this.tr = transform;
            this.bound = bound;
            this.slack = slack;
        }

        public void MoveLayer(Vector3 cameraPosition)
        {
            float cameraRelativeMove = (cameraPosition.x / this.bound) * -1;
            Vector3 newPos = new Vector3(this.originalPosition.x + this.slack * cameraRelativeMove, this.originalPosition.y, this.originalPosition.z);
            this.tr.localPosition = newPos;
        }
    }
}
