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

public class CameraZoomDragScaler : MonoBehaviour
{
    public MouseInputBehaviour dragComp;
    public Camera              targetCam;

    public  float zoomSpeed = 2.0f;
    private float initZoom;

    private float currZoom;
    private float targetZoom;

    public float minMagDrag     = 1.0f;
    public float maxMagDrag     = 3.0f;

    public float maxZoomFactor = 2.0f;
    public float smoothZoomTime = 0.4f;
    public float smoothingClamp = 3.0f;

    public float smoothResetFactor = 3.0f;
    public float resetSpeed     = 5.0f;

    private float zoomVel; //readonly

    bool isZooming = false;

    // Start is called before the first frame update
    void Start()
    {
        if (dragComp == null){
            GameObject.FindObjectOfType<MouseInputBehaviour>();
        }
        dragComp.onDragHandler += OnDragHandler;
        dragComp.onDragFinishHandler += OnDragFinished;

        if (targetCam == null) targetCam = Camera.main;
        initZoom = targetCam.orthographicSize;
    }

    // Update is called once per frame
    void Update()
    {
        if (isZooming == false)
        {
            targetZoom = Mathf.MoveTowards(targetZoom,initZoom,Time.deltaTime * resetSpeed);
        }

        currZoom = Mathf.SmoothDamp(currZoom,
                                    targetZoom,
                                    ref zoomVel,
                                    isZooming ? smoothZoomTime : smoothZoomTime / smoothResetFactor,
                                    smoothingClamp);

        targetCam.orthographicSize = currZoom;

    }

    void OnDragHandler(Vector2 dragDelta)
    {
        if (isZooming == false) isZooming = true;
        float mag = dragDelta.magnitude;
        float interpolant = Mathf.Clamp01(Mathf.InverseLerp(minMagDrag,maxMagDrag, mag));

        targetZoom = Mathfx.Lerp(initZoom,initZoom * maxZoomFactor, interpolant);

    }

    void OnDragFinished(Vector2 dragEnd)
    {
        isZooming = false;
    }
}
