using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;

namespace RecrownedAthenaeum.Render
{
    /// <summary>
    /// A batch used to draw primitive shapes by batching together vertices.
    /// </summary>
    public class PrimitiveBatch : IDisposable
    {
        VertexPositionColor[] vertices;
        int bufferPosition;
        Effect effect;
        PrimitiveType primitiveType;
        private int verticesPerPrimitive;

        /// <summary>
        /// Amount of primitives.
        /// </summary>
        public int primitiveCount;

        GraphicsDevice graphicsDevice;
        bool began;
        bool disposed;

        BasicEffect basicEffect;
        /// <summary>
        /// Creates a batch used to draw primitives.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device used to draw the primitives.</param>
        /// <param name="verticesPerBatch">The amount of vertices every batch can hold before flushing. Default is 450. Should be changed to be the most optimal number if possible to prevent unnecessary resizing. Especially if using strip primitive types.</param>
        public PrimitiveBatch(GraphicsDevice graphicsDevice, int verticesPerBatch = 500)
        {
            vertices = new VertexPositionColor[verticesPerBatch + 1];
            this.graphicsDevice = graphicsDevice;
            basicEffect = new BasicEffect(graphicsDevice);
            basicEffect.VertexColorEnabled = true;
            basicEffect.Projection = Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1);
            basicEffect.World = Matrix.Identity;
            basicEffect.View = Matrix.CreateLookAt(Vector3.Zero, Vector3.Forward, Vector3.Up);
        }

        /// <summary>
        /// Starts the batch. Batch cannot be started twice.
        /// </summary>
        /// <param name="primitiveType">The type of primitive this batch would be drawing.</param>
        /// <param name="effect">Effect to use to render the primitives. Default will use a <see cref="BasicEffect"/> with parameters set up during creation.</param>
        public void Begin(PrimitiveType primitiveType, Effect effect = null)
        {
            if (began) throw new InvalidOperationException("Begin is being called twice before being ended.");
            if (disposed) throw new ObjectDisposedException(this.GetType().Name);
            this.primitiveType = primitiveType;
            switch (primitiveType)
            {
                case PrimitiveType.LineList: verticesPerPrimitive = 2; break;
                case PrimitiveType.TriangleList: verticesPerPrimitive = 3; break;
                case PrimitiveType.LineStrip: verticesPerPrimitive = 1; break;
                case PrimitiveType.TriangleStrip: verticesPerPrimitive = 3; break;
            }
            this.effect = effect ?? basicEffect;
            began = true;
        }

        /// <summary>
        /// Ends the batch. Begin needs to be called before end.
        /// </summary>
        public void End()
        {
            if (disposed) throw new ObjectDisposedException(this.GetType().Name);
            if (!began) throw new InvalidOperationException("Begin must be called before ending.");
            Flush();
            began = false;
        }

        /// <summary>
        /// Adds a vertex position for the primitive being drawn. The batch needs to have beens started before this.
        /// </summary>
        /// <param name="vertex">The vector that represents the vertex.</param>
        /// <param name="color">The color of that vertex.</param>
        public void AddVertex(Vector2 vertex, Color color)
        {
            if (!began) throw new InvalidOperationException("Begin needs to be called before adding vertex.");
            if (disposed) throw new ObjectDisposedException(this.GetType().Name);
            if (primitiveType != PrimitiveType.LineStrip && primitiveType != PrimitiveType.TriangleStrip)
            {
                if (bufferPosition + verticesPerPrimitive >= vertices.Length)
                {
                    if ((bufferPosition % vertices.Length == 0))
                    {
                        Flush();
                    }
                    else
                    {
                        throw new InvalidOperationException("Buffer size doesn't match with primitive type.");
                    }
                }
            }
            else if (bufferPosition + verticesPerPrimitive > vertices.Length)
            {
                throw new InvalidOperationException("Buffer size isn't large enough.");
            }

            vertices[bufferPosition] = new VertexPositionColor(new Vector3(vertex, 0), color);
            bufferPosition++;
        }

        /// <summary>
        /// Flushes the batch. Automatically called if required if using <see cref="PrimitiveType.LineList"/> or <see cref="PrimitiveType.TriangleList"/>. Otherwise, manual flushing is required.
        /// <see cref="primitiveCount"/> is used if not zero. Is reset to zero every flush.
        /// </summary>
        public void Flush()
        {
            if (!began) throw new InvalidOperationException("Begin needs to be called before flushing.");
            if (disposed) throw new ObjectDisposedException(this.GetType().Name);
            if (bufferPosition == 0) return;
            if (primitiveCount == 0) primitiveCount = bufferPosition / verticesPerPrimitive; 
            foreach (EffectPass effectPass in effect.CurrentTechnique.Passes)
            {
                effectPass.Apply();
                graphicsDevice.DrawUserPrimitives(primitiveType, vertices, 0, primitiveCount);
            }
            bufferPosition = 0;
            primitiveCount = 0;
        }

        /// <summary>
        /// Disposes this.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Overridable dispose.
        /// </summary>
        /// <param name="disposing">True for when user called for this to be disposed. False otherwise.</param>
        public virtual void Dispose(bool disposing)
        {
            if (disposed) throw new ObjectDisposedException(this.GetType().Name);
            disposed = true;
            if (disposing && !disposed)
            {
                basicEffect.Dispose();
            }
        }

        /// <summary>
        /// Destructor.
        /// </summary>
        ~PrimitiveBatch()
        {
            Dispose(false);
        }
    }
}
