using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace Texturing
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        KeyboardState priorKeyboardState = Keyboard.GetState();

        Camera camera;

        Matrix world = Matrix.Identity; 
        Matrix worldTranslation = Matrix.Identity; 
        Matrix worldRotation = Matrix.Identity; 

        VertexPositionTexture[] verts;

        Matrix rotation = Matrix.Identity;

        Texture2D texture;

        Effect effect;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            camera = new Camera(this, new Vector3(0, 0, 5),
                Vector3.Zero, Vector3.Up);
            Components.Add(camera);

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            effect = Content.Load<Effect>(@"Effects\Blur");

            // TODO: use this.Content to load your game content here
            // changed for texture
            verts = new VertexPositionTexture[4];
            verts[0] = new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0));
            verts[1] = new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0));
            verts[2] = new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1));
            verts[3] = new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1));

            texture = Content.Load<Texture2D>(@"Textures\John_Carmack");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            KeyboardState keyboardState = Keyboard.GetState();
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed
                || keyboardState.IsKeyDown(Keys.Escape))
                this.Exit();

            // TODO: Add your update logic here
            // Translation
            if (keyboardState.IsKeyDown(Keys.R))
            {
                //world = Matrix.Identity;
                worldTranslation = Matrix.Identity;
                worldRotation = Matrix.Identity;
                rotation = Matrix.Identity;
            }

            if (keyboardState.IsKeyDown(Keys.Left))
                worldTranslation *= Matrix.CreateTranslation(-.01f, 0, 0);
            if (keyboardState.IsKeyDown(Keys.Right))
                worldTranslation *= Matrix.CreateTranslation(+.01f, 0, 0);
            if (keyboardState.IsKeyDown(Keys.Up))
                worldTranslation *= Matrix.CreateTranslation(0, +.01f, 0);
            if (keyboardState.IsKeyDown(Keys.Down))
                worldTranslation *= Matrix.CreateTranslation(0, -.01f, 0);
            if (keyboardState.IsKeyDown(Keys.W))
                worldTranslation *= Matrix.CreateTranslation(0, 0, -1f);
            if (keyboardState.IsKeyDown(Keys.S))
                worldTranslation *= Matrix.CreateTranslation(0, 0, +1f);


            if (keyboardState.IsKeyDown(Keys.D) && !priorKeyboardState.IsKeyDown(Keys.D))
            {
                Console.WriteLine("Rotating clockwise");
                rotation *= Matrix.CreateRotationY(MathHelper.PiOver4 / 120);
                Console.WriteLine(worldRotation);
            }
            if (keyboardState.IsKeyDown(Keys.A) && !priorKeyboardState.IsKeyDown(Keys.A))
            {
                Console.WriteLine("Rotating counter-clockwise");
                rotation *= Matrix.CreateRotationY(-MathHelper.PiOver4 / 120);
            }

            worldRotation *= rotation;

            world = worldRotation * worldTranslation;

            if (keyboardState.IsKeyDown(Keys.C) && !priorKeyboardState.IsKeyDown(Keys.C))
            {
                // Set cullmode to none
                RasterizerState rs = new RasterizerState();
                if (GraphicsDevice.RasterizerState.CullMode == CullMode.None)
                    rs.CullMode = CullMode.CullCounterClockwiseFace;
                else
                    rs.CullMode = CullMode.None;
                GraphicsDevice.RasterizerState = rs;
            }

            priorKeyboardState = keyboardState;
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            // GraphicsDevice is a property of Game 
            // that returns a GraphicsDevice object (!!!!)
            GraphicsDevice.Clear(Color.CornflowerBlue);


            // Pick the technique that we are going to use.
            // Could we "loop" through the Techniques, I wonder?
            effect.CurrentTechnique = effect.Techniques["Textured"];
            // Set the world/view/projection matrices
            Matrix worldViewProjection = world * camera.view * camera.projection;
            effect.Parameters["WorldViewProjection"].SetValue(worldViewProjection);
            effect.Parameters["ColoredTexture"].SetValue(texture);

            // Unchanged
            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                GraphicsDevice.DrawUserPrimitives<VertexPositionTexture>(
                    PrimitiveType.TriangleStrip, verts, 0, 2);
            }
                 

            base.Draw(gameTime);
        }
    }
}
