using UnityEngine;

namespace CodesmithWorkshop.Useful
{
    /// <summary>
    /// Simple behaviour to point a forward of any transform to another one
    /// </summary>
    [ExecuteInEditMode]
    public class ViewportAligner : MonoBehaviour
    {
        [SerializeField]
        private bool _activeUpdate = true;

        [SerializeField]
        private bool _flip = true;

        [SerializeField]
        private float _scaleByDistanceCoef = 1f;
        private float distance = 0f;
		private Vector3 scaleByDistance = new Vector3();

        private Camera _mainCamera = null;

        private void OnEnable()
        {
            _mainCamera = Camera.main;
        }

        private void Start()
        {
            _mainCamera = Camera.main;
        }

        // Update is called once per frame
        private void LateUpdate()
        {
            if (_activeUpdate && _mainCamera)
            {
                transform.rotation = _flip
                    ? _mainCamera.transform.rotation * UtilsClass.k_flipQuaternion
                    : _mainCamera.transform.rotation;

                distance = Vector3.Distance(transform.position, _mainCamera.transform.position);
				scaleByDistance.x = distance * _scaleByDistanceCoef;
				scaleByDistance.y = distance * _scaleByDistanceCoef;
				scaleByDistance.z = distance * _scaleByDistanceCoef;
                transform.localScale = scaleByDistance;
            }
        }
    }
}
