using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;

namespace WaterTest
{
    class Camera
    {
        public Camera(int screenWidth, int screenHeight)
        {
            this.screenWidth = screenWidth;
            this.screenHeight = screenHeight;
        }

        private int screenWidth, screenHeight;

        // Set:
        public Vector3 LookAt { get; set; }
        public Vector3 Position { get; set; }
        public float Distance { get; set; }

        private Vector3 upVector = Vector3.Up;

        public Vector3 DirectionToViewer { get; private set; }
        public Vector3 Tangent { get; private set; }    // Arbitrary vector that is orthogonal to DirectionToViewer

        public Matrix View { get; private set; }
        public Matrix Projection { get; private set; }
        public float FarPlane { get { return farPlane; } }
        public float NearPlane { get { return nearPlane; } }

        private static float farPlane = 100f;
        private static float nearPlane = 0.1f;

        public void SetDirectionToViewer(Vector3 directionToViewer)
        {
            Position = LookAt + directionToViewer * Distance;
        }

        public void SetDistance(float distance)
        {
            Vector3 directionToViewer = Vector3.Normalize(Position - LookAt);
            Distance = distance;
            Position = LookAt + directionToViewer * distance;
        }

        public void SetNewPosition(float x, float z)
        {
            Vector3 lookAt = LookAt;
            lookAt.X = x;
            lookAt.Z = z;
            LookAt = lookAt;
            Position = LookAt + DirectionToViewer * Distance;
        }

        public void Update()
        {
            DirectionToViewer = Vector3.Normalize(Position - LookAt);

            View = Matrix.CreateLookAt(Position, LookAt, upVector);

            Projection = Matrix.CreatePerspectiveFieldOfView(0.23f, (float)screenWidth / (float)screenHeight, nearPlane, farPlane);

            // Note: When viewed from above, this will be wrong!
            Tangent = Vector3.Normalize(Vector3.Cross(DirectionToViewer, upVector));
        }
    }
}
