using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;

namespace SlXnaApp2
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        Model myCube;
        Matrix worldMatrix;
        Matrix viewMatrix;
        Matrix projectionMatrix;
        float rotationXAmount = 0.0f;
        float rotationYAmount = 0.0f;
        //Silverlight Elemente zeichnen
        UIElementRenderer uiRenderer;
        //Silverlight auf Würfel
        bool boSLTexture;
        //Würfel textur speichen
        Texture2D texCube;
        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            myCube = contentManager.Load<Model>("cubetextured");
            //Textur speichern
            texCube = (myCube.Meshes[0].Effects[0] as BasicEffect).Texture;
            boSLTexture = false;
            //DoubleTap erlauben
            TouchPanel.EnabledGestures = GestureType.DoubleTap;

            worldMatrix = Matrix.Identity;
            viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 10.0f), new Vector3(0.0f, 0.0f, 0.0f), Vector3.Up);
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.AspectRatio, 1.0f, 100.0f);

            // Start the timer
            timer.Start();

            //Durchgehend laufen lassen
            this.TextAnim1.RepeatBehavior = System.Windows.Media.Animation.RepeatBehavior.Forever;
            //Starten
            this.TextAnim1.Begin();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            rotationYAmount += MathHelper.ToRadians(1.0f);
            rotationXAmount += MathHelper.ToRadians(1.0f);
            while (TouchPanel.IsGestureAvailable)
            {
                //Die aktuelle Geste auslesen
                GestureSample curGesture = TouchPanel.ReadGesture();
                //Gestentyp prüfen
                switch (curGesture.GestureType)
                {
                    //DoubleTap-Geste auswerten
                    case GestureType.DoubleTap:
                        boSLTexture = !boSLTexture;
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            //Den Hintergund zeichen
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);
            //Skalierung des Würfels
            float Skalierung = 1.0f;
            //Die Silverlight Elemente zum Zeichnen vorbereiten
            uiRenderer.Render();
            //Textur prüfen
            if (!boSLTexture)
            {
                //Silverlight Elemente "normal" ausgeben
                spriteBatch.Begin();
                spriteBatch.Draw(uiRenderer.Texture, Vector2.Zero, Color.White);
                spriteBatch.End();
            }
            else//Den Würfel vergrössern
                Skalierung = 2.0f;

            // TODO: Add your drawing code here
            foreach (ModelMesh m in myCube.Meshes)
            {
                foreach (BasicEffect effect in m.Effects)
                {
                    if (boSLTexture)//Silverlight Elemente als Textur für den Würfel verwenden
                        effect.Texture = uiRenderer.Texture;
                    else
                        effect.Texture = texCube;
                    effect.EnableDefaultLighting();
                    effect.World = Matrix.CreateScale(Skalierung) *
                        Matrix.CreateRotationX(rotationXAmount) *
                        Matrix.CreateRotationY(rotationYAmount) *
                        Matrix.CreateTranslation(Vector3.Zero);
                    effect.View = viewMatrix;
                    effect.Projection = projectionMatrix;
                }
                m.Draw();
            }
        }

        private void PhoneApplicationPage_LayoutUpdated(object sender, System.EventArgs e)
        {
        	if(uiRenderer == null || LayoutRoot.ActualWidth > 0 && LayoutRoot.ActualHeight > 0)
                uiRenderer = new UIElementRenderer(LayoutRoot, (int)LayoutRoot.ActualWidth, (int)LayoutRoot.ActualHeight);
        }
    }
}