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

public class CameraFollow : MonoBehaviour
{
    public BaseCell target;
    Vector2 viewMargins = new Vector2(5,5);
    Rect targetViewRect;

    Vector3 positionVelocity;
    float cameraSizeVelocity;

    Camera camera;

    void Start()
    {
        if (!camera)
            camera = GetComponent<Camera>();
    }

    void FixedUpdate()
    {
        targetViewRect.width = 0;
        targetViewRect.height = 0;
        targetViewRect.center = target.transform.position;
        CalculateRect(target);
        targetViewRect.xMin -= viewMargins.x;
        targetViewRect.xMax += viewMargins.x;

        targetViewRect.yMin -= viewMargins.y;
        targetViewRect.yMax += viewMargins.y;

        Vector3 targetPosition = targetViewRect.center;
        targetPosition += (Vector3)target.GetComponent<Rigidbody2D>().velocity * Mathf.Max(targetViewRect.width, targetViewRect.height) * 0.1f;
        targetPosition.z = transform.position.z;
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref positionVelocity, 1f);

        var targetHeight = Mathf.Max(targetViewRect.height, targetViewRect.width / camera.aspect);
        camera.orthographicSize = Mathf.SmoothDamp(camera.orthographicSize, targetHeight, ref cameraSizeVelocity, 2);
    }

    void CalculateRect(BaseCell cell)
    {
        foreach (var connection in cell.possibleConnections)
        {
            var nextCell = connection.cell;
            if (nextCell)
            {
                CalculateRect(connection.cell);
            }
        }
        targetViewRect.xMin = Mathf.Min(targetViewRect.xMin, cell.transform.position.x);
        targetViewRect.xMax = Mathf.Max(targetViewRect.xMax, cell.transform.position.x);

        targetViewRect.yMin = Mathf.Min(targetViewRect.yMin, cell.transform.position.y);
        targetViewRect.yMax = Mathf.Max(targetViewRect.yMax, cell.transform.position.y);
    }
}
