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

public class BackgroundScroller : MonoBehaviour
{
    public Rigidbody2D target;
    public Camera      targetCam;
    private Renderer _renderer;
    public Vector2 uv = Vector2.zero;
    public Vector2 tiling = Vector2.one;
    Vector2 scaleFactor = Vector2.one;

    float initProjectionSize;


    // Start is called before the first frame update
    void Start()
    {
        _renderer = gameObject.GetComponent<Renderer>();
        initProjectionSize = targetCam.orthographicSize;
    }

    // Update is called once per frame
    void Update()
    {
        if (UIController._isPaused == false)
        ScaleByCameraBounds();   // TIME RUNNIING OUT lmao
        // TileByCameraZoom();
        scaleFactor.x = _renderer.bounds.size.x;
        scaleFactor.y = _renderer.bounds.size.y;
        if (_renderer && target != null)
        {
                Vector2 textureOffset = target.velocity;
                textureOffset /= (scaleFactor);
                uv += textureOffset * Time.deltaTime;

                transform.position = new Vector3(target.transform.position.x,
                                                 target.transform.position.y,
                                                 transform.position.z);
        }
        _renderer.material.mainTextureOffset = uv;
        _renderer.material.mainTextureScale  = tiling;
    }

    void ScaleByCameraBounds()
    {
        float depth = transform.position.z;
        Vector3 screenBottomLeft = new Vector3(0,0,depth);
        Vector3 screenTopRight   = new Vector3(Screen.width,Screen.height,depth);

        Vector3 worldbottomLeft = targetCam.ScreenToWorldPoint(screenBottomLeft);
        Vector3 worldtopRight   = targetCam.ScreenToWorldPoint(screenTopRight);
        Vector3 screenDiag      = worldtopRight - worldbottomLeft;

        float xScale = screenDiag.x;
        float yScale = screenDiag.y;

        transform.localScale = new Vector3(xScale,yScale,1.0f);
    }

    void TileByCameraZoom()
    {
        float factor = targetCam.orthographicSize / initProjectionSize;
        tiling = Vector2.one * factor;
        uv +=  (Vector2.one * 0.5f);
        uv -=  (Vector2.one * 0.5f) * factor;
    }
}
