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;

namespace Negative
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;  // Initialized in the constructor, but not directly used by out code.
        SpriteBatch spriteBatch;

        // 1. We need a "Camera".
        //    Initialize the camera to sit out from the middle of the screen, 
        //    aimed at the center, and with its "up" in the up direction of the screen.
        //    Add it to the Game's Components to have its Update called.
        public Matrix view = Matrix.CreateLookAt(
            new Vector3(0, 0, 5), // Camera position
            Vector3.Zero, // Camera target
            Vector3.Up);  // Camera's orientation, i.e. its "up".
        public Matrix projection; //   Initialized in Initialize()

        // 2. Vertices that we will use to display on the screen.
        //    Set up in LoadContent.
        //VertexPositionColor[] verts;
        VertexPositionTexture[] verts;
        Texture2D texture;


        // XNA 4.
        // Initialized in LoadContent and used in Draw.
        //BasicEffect effect;
        Effect effect;

        KeyboardState priorKeyboardState = Keyboard.GetState();

        // 3. Add Transformations
        Matrix world = Matrix.Identity;
        Matrix worldTranslation = Matrix.Identity;
        Matrix worldRotation = Matrix.Identity;
        const float ROTATION_SPEED = MathHelper.PiOver4 / 120;  // rotation speed
        const float TRANSLATION_SPEED = 0.01f; // translation speed

        Matrix rotation = Matrix.Identity;

        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()
        {

            projection = Matrix.CreatePerspectiveFieldOfView(
                   MathHelper.PiOver4, // field angle
                // aspect ratio
                   (float)Window.ClientBounds.Width / (float)Window.ClientBounds.Height,
                   1, // near cutoff
                   100); // far cutoff

            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()
        {
            // TODO: use this.Content to load your game content here
            // 2.  Set up the vertex array.
            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));

            // Load the effect
            effect = Content.Load<Effect>(@"Effects\Negative");
            // Load the texture
            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

            // Reset
            if (keyboardState.IsKeyDown(Keys.R))
            {
                //world = Matrix.Identity;
                worldTranslation = Matrix.Identity;
                worldRotation = Matrix.Identity;
                rotation = Matrix.Identity;
            }

            // Translation
            if (keyboardState.IsKeyDown(Keys.Left))
                worldTranslation *= Matrix.CreateTranslation(-TRANSLATION_SPEED, 0, 0);
            if (keyboardState.IsKeyDown(Keys.Right))
                worldTranslation *= Matrix.CreateTranslation(+TRANSLATION_SPEED, 0, 0);
            if (keyboardState.IsKeyDown(Keys.Up))
                worldTranslation *= Matrix.CreateTranslation(0, +TRANSLATION_SPEED, 0);
            if (keyboardState.IsKeyDown(Keys.Down))
                worldTranslation *= Matrix.CreateTranslation(0, -TRANSLATION_SPEED, 0);

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

            worldRotation *= rotation;

            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.Clear(Color.CornflowerBlue);

            //effect.World = Matrix.Identity;
            //effect.World = worldRotation * worldTranslation;
            //effect.View = view;
            //effect.Projection = projection;
            //effect.VertexColorEnabled = true;

            effect.CurrentTechnique = effect.Techniques["Technique1"];
            effect.Parameters["World"].SetValue(worldRotation * worldTranslation);
            effect.Parameters["View"].SetValue(view);
            effect.Parameters["Projection"].SetValue(projection);
            effect.Parameters["ColoredTexture"].SetValue(texture);


            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();  // XNA 4.0
                GraphicsDevice.DrawUserPrimitives<VertexPositionTexture>(
                    PrimitiveType.TriangleStrip, // How to interpret the vertices
                    verts, // array of vertices
                    0, // offset into the array
                    2); // number of primitives
            }

            base.Draw(gameTime);
        }
    }
}
