using UnityEngine;

namespace ScrambleKit.CameraControl
{
    public class CameraHorizDualForwardFocus : MonoBehaviour
    {
        // Using Dual Forward Focus logic described here:
        // https://www.gamasutra.com/blogs/ItayKeren/20150511/243083/Scroll_Back_The_Theory_and_Practice_of_Cameras_in_SideScrollers.php

        public Transform Subject;
        public float ForwardFocusDist = 1.5f;
        public float ReverseThreshold = 3f;

        public float CameraVelocity = 5;
        public float CameraAccel = 15;

        private float cameraAheadBy;
        private bool movingRight;

        private float offsetFromSubject;

        void FixedUpdate()
        {
            if (Subject == null)
                return;

            CalcCameraAheadBy();
            if (NeedsReversal())
            {
                movingRight = !movingRight;
                CalcCameraAheadBy();
            }

            if (NeedsToMove())
                MoveToSubject();
            else
                Stop();
        }


        private void CalcCameraAheadBy()
        {
            cameraAheadBy = (movingRight) ?
                            transform.position.x - Subject.position.x :
                            Subject.position.x - transform.position.x;
        }

        private bool NeedsReversal()
        {
            return (cameraAheadBy > ForwardFocusDist + ReverseThreshold);
        }

        private bool NeedsToMove()
        {
            return cameraAheadBy < ForwardFocusDist;
        }

        private void MoveToSubject()
        {
            int forwardDir = ((movingRight) ? 1 : -1);
            float targetPosition = Subject.position.x + (ForwardFocusDist * forwardDir);
            float targetOffset = targetPosition - Subject.position.x;

            float gap = targetOffset - offsetFromSubject;
            float closeGap = Mathf.Clamp(gap, -CameraVelocity * Time.fixedDeltaTime, CameraVelocity * Time.fixedDeltaTime);

            offsetFromSubject += closeGap;

            transform.position = new Vector3(Subject.position.x + offsetFromSubject, transform.position.y, transform.position.z);
        }

        private void Stop()
        {
            offsetFromSubject = transform.position.x - Subject.position.x;
        }
        
    }

}