/*
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 UnityEngine;
using EyeSkills;

namespace EyeSkills
{
    /// <summary>
    /// Micro controller misalignment. Manually adjust the alignment of the world perceived by each eye.
    /// Add this as a child script of the EyeSkills Camera Rig in the Unity Editor.
    /// </summary>
    public class MicroControllerMisalignment : MicroController
    {
        protected AudioManager audioManager;
        private EyeSkillsCameraRigEditMode parentManager;
        public GameObject leftEye, rightEye;
        private EyeSkillsInput esInput;
        private bool active = false, eyeUnlocked = false;
        private StereoTargetEyeMask eyeMask;
        private EyeSkillsCameraRig cameraRig;
        private float rotationInc = 0.1f;

        public void Start()
        {
            audioManager = AudioManager.instance;
            esInput = EyeSkillsInput.instance;
            eyeMask = StereoTargetEyeMask.None;
            cameraRig = gameObject.GetComponent<EyeSkillsCameraRig>();
        }

        public override void Shutdown()
        {
            active = false;
            //leftEye.transform.Rotate(Vector3.forward - leftEye.transform.eulerAngles);
            //rightEye.transform.Rotate(Vector3.forward - rightEye.transform.eulerAngles);
            parentManager.MicroControllerShutdown();
        }

        public override void Startup(EyeSkillsCameraRigEditMode _parent)
        {
            active = true;
            audioManager.Say("RealignmentAvailable");
            parentManager = _parent;
        }

        private void UnlockRightEye()
        {
            eyeMask = StereoTargetEyeMask.Right;
            Debug.Log("Right Eye Unlocked");
        }

        private void UnlockLeftEye()
        {
            eyeMask = StereoTargetEyeMask.Left;
            Debug.Log("Left Eye Unlocked");
        }

        private bool EyeUnlocked()
        {
            return (eyeMask != StereoTargetEyeMask.None);
        }

        private void RotateEye(int direction)
        {
            if (eyeMask == StereoTargetEyeMask.Left)
            {
                leftEye.transform.Rotate(new Vector3(0f, direction * rotationInc, 0f)); //Is this relative?               
            }
            else if (eyeMask == StereoTargetEyeMask.Right)
            {
                rightEye.transform.Rotate(new Vector3(0f, direction * rotationInc, 0f));
            }
        }

        public void Update()
        {
            // Here we have our actual control interface - to add and remove our cues.
            // This is really annoying having this extra Update logic here, but enabling/disabling the script was making
            // life really complex- it doesn't happen instantaneously, but requires waiting for a full iteration AFAIK
            if (active)
            {
                // Make this two mode. Long press to detect which eye to unlock. Then start listening for regular buttons to move the camera smoothly
                // we can only unlock once
                if (esInput.GetLongButtonPress("EyeSkills Right") && (!eyeUnlocked))
                {
                    UnlockRightEye();
                    eyeUnlocked = true;
                }
                else if (esInput.GetLongButtonPress("EyeSkills Left") && (!eyeUnlocked))
                {
                    UnlockLeftEye();
                    eyeUnlocked = true;
                }
                else if (Input.GetButton("EyeSkills Confirm") || (Input.GetButton("EyeSkills Cancel")))
                {
                    Vector3 euler = cameraRig.GetEyeAngle(eyeMask);
                    Debug.Log("Angle between eyes is " + euler.y + " degrees.");
                    if (eyeMask == StereoTargetEyeMask.Left)
                    {
                        cameraRig.config.leftEyeMisalignmentAngle = euler;
                        Debug.Log("Saving left eye calibration");
                    }
                    else
                    {
                        cameraRig.config.rightEyeMisalignmentAngle = euler;
                        Debug.Log("Saving right eye calibration");
                    }


                    eyeMask = StereoTargetEyeMask.None;
                    Shutdown();
                }

                if (EyeUnlocked())
                {
                    // Currently only works in horizontal                
                    if (Input.GetButton("EyeSkills Right"))
                    {
                        Debug.Log("Rotating Right....");
                        RotateEye(-1);
                    }
                    else if (Input.GetButton("EyeSkills Left"))
                    {
                        Debug.Log("Rotating Left....");
                        RotateEye(1);
                    }
                }
            }
        }
    }
}