using System;
using UnityEngine;

namespace SicknessReduction.Visual
{
    public class VirtualNose : MonoBehaviour
    {
        public GameObject prefabToSpawn;

        public bool adjustToIpd = true;
        public Vector3 paddingAt58;
        public Vector3 scaleAt58;
        public Vector3 paddingAt70;
        public Vector3 scaleAt70;

        private Camera cam;
        private GameObject nose;
        private IpdInfo ipdInfo;

        private void OnEnable()
        {
            cam = Camera.main;
            if (cam == null)
            {
                Debug.LogError("No main camera found. Cannot place virtual nose!");
                return;
            }

            ipdInfo = GetComponentInParent<IpdInfo>();
            if (ipdInfo == null)
            {
                Debug.LogError("No IPD Info found as parent of virtual nose");
            }

            if (adjustToIpd) ipdInfo.onIpdChanged += AdjustToIpd;

            nose = Instantiate(prefabToSpawn, cam.transform);
            nose.transform.localPosition = Vector3.forward * cam.nearClipPlane;
        }

        private void AdjustToIpd(float ipdMeters)
        {
            var ipdMm = Mathf.Round(ipdMeters * 1000f);
            var ipdFactor = (ipdMm - 58f) / 12f;
            var padding = Vector3.Lerp(paddingAt58, paddingAt70, ipdFactor);
            nose.transform.localScale = Vector3.Lerp(scaleAt58, scaleAt70, ipdFactor);
            nose.transform.localPosition = Vector3.forward * cam.nearClipPlane + padding;
        }

        private void OnDisable()
        {
            ipdInfo.onIpdChanged -= AdjustToIpd;
            if (nose == null) return;
            Destroy(nose);
        }
    }
}