using UnityEngine;
using System;
using System.Collections.Generic;
using System.Reflection;
using mgaia.Utils;

namespace mgaia.Editor
{
    /// <summary>
    /// Behaviour da câmera para desenhar bordas
    /// </summary>
    /// <owner>Victor</owner>
    public class OrtographicCameraBorder : MonoBehaviour
    {
        public Color borderColor = Color.yellow;

#if UNITY_EDITOR
        private void OnDrawGizmos()
        {
            Camera camera = gameObject.camera;

            if (!camera.isOrthoGraphic)
            {
                Debug.LogError("O behaviour OrtographicCameraBorder só deve ser utilizado para câmeras com projeções ortogonais!");
            }
            else
            {
                float gameWidth, gameHeight, aspect;

                EditorHelper.GetGameViewSize(out gameWidth, out gameHeight, out aspect);

                Gizmos.color = borderColor;

                float cameraHeight = camera.orthographicSize * 2;
                float cameraWidth = cameraHeight * aspect;

                Vector3 cameraDimensionVector = new Vector3(cameraWidth, cameraHeight);

                Vector3 topRightCoordinate = transform.position + cameraDimensionVector / 2;
                Vector3 topLeftCoordinate = topRightCoordinate - new Vector3(cameraDimensionVector.x, 0);
                Vector3 bottomLeftCoordinate = transform.position - cameraDimensionVector / 2;
                Vector3 bottomRightCoordinate = bottomLeftCoordinate + new Vector3(cameraDimensionVector.x, 0);

                Vector3[] frontalCoordinates = new Vector3[] { bottomLeftCoordinate, bottomRightCoordinate, topRightCoordinate, topLeftCoordinate };

                DrawSquare(frontalCoordinates);

                Vector3[] zCoordinates = new Vector3[frontalCoordinates.Length];
                for (var idx = 0; idx < zCoordinates.Length; idx++)
                {
                    zCoordinates[idx] = frontalCoordinates[idx] + new Vector3(0, 0, camera.farClipPlane);

                    Gizmos.DrawLine(frontalCoordinates[idx], zCoordinates[idx]);
                }

                DrawSquare(zCoordinates);
            }
        }

        /// <summary>
        /// Desenha um quadrado a partir de um vetor de coordenadas
        /// </summary>
        /// <owner>Victor</owner>
        private void DrawSquare(Vector3[] coordinates)
        {
            for (var idx = 0; idx < coordinates.Length; idx++)
            {
                Vector3 nextCoordinate = default(Vector3);

                if (idx < coordinates.Length - 1)
                {
                    nextCoordinate = coordinates[idx + 1];
                }
                else
                {
                    nextCoordinate = coordinates[0];
                }

                Gizmos.DrawLine(coordinates[idx], nextCoordinate);
            }
        }
#endif
    }
}