/*
Copyright 2019 Dr. Thomas Benjamin Senior, Michael Zoeller 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using EyeSkills.ImageEffects;
using UnityEngine.SpatialTracking;

namespace EyeSkills
{
    /// <summary>
    /// The EyeSkills camera rig. This contains a lot of the basic parts you need to alter how the virtual world is perceived by the participant.
    /// Look to the MicroControllers for examples of usage.
    /// </summary>
    public class EyeSkillsCameraRig : MonoBehaviour
    {
        [System.Serializable]
        public class CameraRigConfig : ConfigBase
        {
            public float binocularSuppressionRatio;
            public bool leftEyeIsStrabismic;
            public bool rightEyeIsStrabismic;
            public Vector3 leftEyeMisalignmentAngle;
            public Vector3 rightEyeMisalignmentAngle;
            public float depthPerceptionAccuracy;
            public float leastMisalignmentBeforeFusionLost;
        }

        public CameraRigConfig config;

        public bool trackLeftEyeRotation, trackRightEyeRotation;
        public bool compensateEyeMisalignment;
        public bool compensateBinocularSuppression;

        GameObject left, right, cameraLeft, cameraRight;

        IEnumerator _fixCamera(GameObject go)
        {
            Quaternion r = go.transform.rotation;
            yield return new WaitForSeconds(1f);
            go.transform.rotation = r;
        }

        /// <summary>
        /// Reset the camera to its initial position.
        /// </summary>
        public void ResetCamera()
        {
            left = GameObject.Find("Left");
            right = GameObject.Find("Right");
            cameraLeft = GameObject.Find("Main Camera Left");
            cameraRight = GameObject.Find("Main Camera Right");

            SetRightEyePositionOnly();
            SetLeftEyePositionOnly();

            if (trackLeftEyeRotation)
            {
                SetLeftEyeRotationAndPosition();
            }

            if (trackRightEyeRotation)
            {
                SetRightEyeRotationAndPosition();
            }

            StartCoroutine(_go());
        }

        void Awake()
        {
            ResetCamera();
        }


        /// <summary>
        /// Link the camera to the movement of the head
        /// </summary>
        /// <param name="camera">Camera.</param>
        /// <param name="trackingType">Tracking type.</param>
        private void SetEyeTracking(GameObject camera, TrackedPoseDriver.TrackingType trackingType)
        {
            TrackedPoseDriver driver = camera.GetComponentInChildren<TrackedPoseDriver>();
            if (driver != null)
            {
                driver.trackingType = trackingType;
            }
            else
            {
                Debug.Log("ERROR: Could not find TrackedPoseDriver for " + camera);
            }
        }

        /// <summary>
        /// Sets the right eye to follow rotation and position.
        /// </summary>
        public void SetRightEyeRotationAndPosition()
        {
            SetEyeTracking(cameraRight, TrackedPoseDriver.TrackingType.RotationAndPosition);
        }

        /// <summary>
        /// Sets the left eye to follow rotation and position.
        /// </summary>
        public void SetLeftEyeRotationAndPosition()
        {
            SetEyeTracking(cameraLeft, TrackedPoseDriver.TrackingType.RotationAndPosition);
        }

        /// <summary>
        /// Sets the left eye to follow position only.
        /// </summary>
        public void SetLeftEyePositionOnly()
        {
            SetEyeTracking(cameraLeft, TrackedPoseDriver.TrackingType.PositionOnly);
        }

        /// <summary>
        /// Sets the right eye to follow position only.
        /// </summary>
        public void SetRightEyePositionOnly()
        {
            SetEyeTracking(cameraRight, TrackedPoseDriver.TrackingType.PositionOnly);
        }

        /// <summary>
        /// Rotate the specified eye by the provided vector.
        /// </summary>
        /// <param name="eyeMask">Eye mask.</param>
        /// <param name="vector">Vector.</param>
        public void Rotate(StereoTargetEyeMask eyeMask, Vector3 vector)
        {
            // BUG: dangerous, what with "both"?
            GameObject cam = (eyeMask == StereoTargetEyeMask.Left) ? cameraLeft : cameraRight;
            cam.transform.Rotate(vector);
        }

        /// <summary>
        /// Rotates the left eye.
        /// </summary>
        /// <param name="vector">Vector.</param>
        public void RotateLeftEye(Vector3 vector)
        {
            Rotate(StereoTargetEyeMask.Left, vector);
        }

        /// <summary>
        /// Rotates the right eye.
        /// </summary>
        /// <param name="vector">Vector.</param>
        public void RotateRightEye(Vector3 vector)
        {
            Rotate(StereoTargetEyeMask.Right, vector);
        }

        /// <summary>
        /// Straightens the eye.
        /// </summary>
        /// <param name="_camera">Camera.</param>
        private void StraightenEye(GameObject _camera)
        {
            _camera.transform.Rotate(Vector3.zero - _camera.transform.eulerAngles);
        }

        /// <summary>
        /// Straightens the right eye.
        /// </summary>
        public void StraightenRightEye()
        {
            StraightenEye(cameraRight);
        }

        /// <summary>
        /// Straightens the left eye.
        /// </summary>
        public void StraightenLeftEye()
        {
            StraightenEye(cameraLeft);
        }

        /// <summary>
        /// Returns the direction of the eye in degrees. Note, the values are from 0 - 360 degrees as they measure the angle clockwise from the origin.
        /// </summary>
        /// <returns>The eye angle.</returns>
        /// <param name="_eye">Eye.</param>
        public Vector3 GetEyeAngle(StereoTargetEyeMask _eye)
        {
            if (_eye == StereoTargetEyeMask.Left)
                return cameraLeft.transform.rotation.eulerAngles;

            if (_eye == StereoTargetEyeMask.Right)
                return cameraRight.transform.rotation.eulerAngles;

            Debug.Log("Requested EyeAngle for unknown eye");
            return Vector3.zero;
        }

        /// <summary>
        /// Returns the angle of the eye in degrees around the vertical axis (looking from left to right) where values are from 0 to +180 when looking right and 0 to -180 when looking left
        /// </summary>
        /// <returns>The eye angle human readable.</returns>
        /// <param name="_eye">Eye.</param>
        public float HorizontalEyeAngleHumanReadable(StereoTargetEyeMask _eye)
        {
            Vector3 angle = GetEyeAngle(_eye);

            if (angle.y > 180)
                return -(360 - angle.y);

            return angle.y;
        }

        /// <summary>
        /// Gets the angle between the left and right eyes. OBSOLETE
        /// </summary>
        /// <returns>The angle between eyes.</returns>
        public Vector3 GetAngleBetweenRightEyeRelativeToLeftEye()
        {
            Quaternion relative = Quaternion.Inverse(cameraLeft.transform.rotation) * cameraRight.transform.rotation;
            return relative.eulerAngles;
        }

        /// <summary>
        /// Provide post-processed control over the perceived brightness of each camera.
        /// 1 is normal.  0 is black. 2 is doubled brightness.
        /// </summary>
        public void SetCameraBrightness(StereoTargetEyeMask _eye, float _brightness)
        {
            Brightness script;

            if (_eye == StereoTargetEyeMask.Left)
                script = cameraLeft.GetComponent<Brightness>();
            else if (_eye == StereoTargetEyeMask.Right)
                script = cameraRight.GetComponent<Brightness>();
            else
                return;

            script.enabled = true;
            script.brightness = _brightness;
        }

        /// <summary>
        /// Sets the binocular suppression ratio.
        /// If ratio larger 0 we dim the right eye relative to the full strength left eye.
        /// If ratio less 0 we dim the left eye relative to the full strength right eye.
        /// </summary>
        /// <param name="ratio">Ratio.</param>
        public void SetBinocularSuppressionRatio(float ratio)
        {
            if (ratio > 0)
                SetCameraBrightness(StereoTargetEyeMask.Right, ratio);
            else if (ratio < 0)
                // the "direction" was just indicating eye. Keep only the amount.
                SetCameraBrightness(StereoTargetEyeMask.Left, -ratio);
        }

        public bool CameraReady()
        {
            return (cameraLeft != null);
        }

        /// <summary>
        /// Disables the left eye.
        /// </summary>
        public void DisableLeftEye()
        {
            left.SetActive(false);
        }

        /// <summary>
        /// Disables the right eye.
        /// </summary>
        public void DisableRightEye()
        {
            right.SetActive(false);
        }

        /// <summary>
        /// Enables the left eye.
        /// </summary>
        public void EnableLeftEye()
        {
            left.SetActive(true);
        }

        /// <summary>
        /// Enables the right eye.
        /// </summary>
        public void EnableRightEye()
        {
            right.SetActive(true);
        }

        /// <summary>
        /// Rotates to straighten eye.
        /// </summary>
        /// <returns>The to straighten eye.</returns>
        /// <param name="eyeMask">Eye mask.</param>
        /// <param name="rate">Rate.</param>
        public Quaternion RotateToStraightenEye(StereoTargetEyeMask eyeMask, float rate)
        {
            Quaternion forward = Quaternion.Euler(Vector3.zero);
            GameObject currentCam = (eyeMask == StereoTargetEyeMask.Left) ? cameraLeft : cameraRight;
            currentCam.transform.rotation = Quaternion.RotateTowards(currentCam.transform.rotation, forward, rate);
            return currentCam.transform.rotation;
        }

        IEnumerator _go()
        {
            yield return new WaitForSeconds(0.1f);

            cameraLeft.GetComponent<Brightness>().enabled = false;
            cameraRight.GetComponent<Brightness>().enabled = false;

            if (compensateBinocularSuppression)
            {
                Debug.Log("CameraRig: Compensating for binocular suppression with " + config.binocularSuppressionRatio);
                SetBinocularSuppressionRatio(config.binocularSuppressionRatio);
            }

            if (compensateEyeMisalignment)
            {
                GameObject go;

                if (config.leftEyeIsStrabismic)
                {
                    Debug.Log("CameraRig: Compensating for left eye misalignment (" + config.leftEyeMisalignmentAngle + ")");
                    go = GameObject.Find("Left");
                    go.transform.localEulerAngles = config.leftEyeMisalignmentAngle;
                }

                if (config.rightEyeIsStrabismic)
                {
                    Debug.Log("CameraRig: Compensating for right eye misalignment (" + config.rightEyeMisalignmentAngle + ")");
                    go = GameObject.Find("Right");
                    go.transform.localEulerAngles = config.rightEyeMisalignmentAngle;
                }
            }
        }
    }
}
