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

namespace GraphiXNA.Graphics.Library
{
    public class PlaneXZ : Object3D
    {
        public PlaneXZ(GraphicsDevice graphicsDevice, float xSize, float zSize, float xCenter, float yCenter, float zCenter, int xSegments, int zSegments)
            : base(graphicsDevice)
        {
            int xVerts = xSegments + 1;
            int zVerts = zSegments + 1;

            this.VertexStride = VertexPositionTexture.SizeInBytes;
            this.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionTexture.VertexElements);
            this.BaseVertex = 0;
            this.PrimitiveType = PrimitiveType.TriangleList;
            this.PrimitiveCount = xSegments * zSegments * 2;
            this.NumberOfVertices = xVerts * zVerts;

            float dx = xSize / (float)xVerts;
            float dz = zSize / (float)zVerts;

            //float width = (float)numCellCols * dx;
            //float depth = (float)numCellRows * dz;

            VertexPositionTexture[] verts = new VertexPositionTexture[NumberOfVertices];

            int k = 0;
            for (float i = 0; i < xVerts; ++i)
            {
                for (float j = 0; j < zVerts; ++j)
                {
                    // Negate the depth coordinate to put in quadrant four.  
                    // Then offset to center about coordinate system.
                    verts[k].Position.X = xCenter + (2 * i - xSegments) * dx;
                    verts[k].Position.Z = zCenter + (2 * j - zSegments) * dz;
                    verts[k].Position.Y = yCenter;

                    verts[k].TextureCoordinate.X = i / xVerts;
                    verts[k].TextureCoordinate.Y = j / zVerts;

                    ++k; // Next vertex
                }
            }

            int[] indices = new int[PrimitiveCount * 3];

            // Generate indices for each quad.
            k = 0;
            for (int i = 0; i < xSegments; ++i)
            {
                for (int j = 0; j < zSegments; ++j)
                {
                    indices[k] = i * zVerts + j;
                    indices[k + 1] = i * zVerts + j + 1;
                    indices[k + 2] = (i + 1) * zVerts + j;

                    indices[k + 3] = (i + 1) * zVerts + j;
                    indices[k + 4] = i * zVerts + j + 1;
                    indices[k + 5] = (i + 1) * zVerts + j + 1;

                    // next quad
                    k += 6;
                }
            }

            VertexBuffer = new VertexBuffer(graphicsDevice, verts.Length * VertexPositionTexture.SizeInBytes, BufferUsage.WriteOnly);
            this.VertexBuffer.SetData<VertexPositionTexture>(verts);

            IndexBuffer = new IndexBuffer(graphicsDevice, 4 * indices.Length, BufferUsage.WriteOnly, IndexElementSize.ThirtyTwoBits);
            IndexBuffer.SetData<int>(indices);
        }

    }
}
