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 System.Windows.Media.Animation;

namespace SlXnaApp3
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        //Würfel
        Model myCube;
        //Welt
        Matrix worldMatrix;
        //Kamera
        Matrix viewMatrix;
        //Linse
        Matrix projectionMatrix;
        //Silverlight Elemente
        UIElementRenderer uiRenderer;
        //Hintergundfarbe für Theme
        Color clrBackground;
        //Kamera "Oben"
        Vector3 v3CamUp = Vector3.Up;
        #region ModelViewerDemo_4_0_Mango Beispiel
        // The position of the camera
        public static readonly DependencyProperty CameraXProperty =
            DependencyProperty.Register("CameraX", typeof(double), typeof(GamePage), new PropertyMetadata(1.0));
        public static readonly DependencyProperty CameraYProperty =
            DependencyProperty.Register("CameraY", typeof(double), typeof(GamePage), new PropertyMetadata(2.0));
        public static readonly DependencyProperty CameraZProperty =
            DependencyProperty.Register("CameraZ", typeof(double), typeof(GamePage), new PropertyMetadata(2.5));

        public double CameraX
        {
            get { return (double)GetValue(CameraXProperty); }
            set { SetValue(CameraXProperty, value); }
        }

        public double CameraY
        {
            get { return (double)GetValue(CameraYProperty); }
            set { SetValue(CameraYProperty, value); }
        }

        public double CameraZ
        {
            get { return (double)GetValue(CameraZProperty); }
            set { SetValue(CameraZProperty, value); }
        }

        public Vector3 CameraPosition
        {
            get { return new Vector3((float)CameraX, (float)CameraY, (float)CameraZ); }
        }
        private readonly TimeSpan cameraAnimationDuration = TimeSpan.FromSeconds(2.0);
        
        private Storyboard cameraPositionStoryboard;

        public void AnimateCameraPosition(Vector3 newPosition)
        {
            if (cameraPositionStoryboard != null)
                cameraPositionStoryboard.Stop();

            // Create the storyboard and set us as the target
            cameraPositionStoryboard = new Storyboard();
            Storyboard.SetTarget(cameraPositionStoryboard, this);
            cameraPositionStoryboard.Completed += (s, e) => cameraPositionStoryboard = null;

            // Create the easing function we'll apply to the animations
            IEasingFunction easingFunction = new QuadraticEase { EasingMode = EasingMode.EaseInOut };

            // Create animations for each of the axis
            DoubleAnimation xAnimation = new DoubleAnimation
            {
                From = CameraX,
                To = newPosition.X,
                Duration = cameraAnimationDuration,
                EasingFunction = easingFunction
            };
            DoubleAnimation yAnimation = new DoubleAnimation
            {
                From = CameraY,
                To = newPosition.Y,
                Duration = cameraAnimationDuration,
                EasingFunction = easingFunction
            };
            DoubleAnimation zAnimation = new DoubleAnimation
            {
                From = CameraZ,
                To = newPosition.Z,
                Duration = cameraAnimationDuration,
                EasingFunction = easingFunction
            };

            // Set the target properties of the animations
            Storyboard.SetTargetProperty(xAnimation, new PropertyPath(CameraXProperty));
            Storyboard.SetTargetProperty(yAnimation, new PropertyPath(CameraYProperty));
            Storyboard.SetTargetProperty(zAnimation, new PropertyPath(CameraZProperty));

            // Add the animations to the storyboard
            cameraPositionStoryboard.Children.Add(xAnimation);
            cameraPositionStoryboard.Children.Add(yAnimation);
            cameraPositionStoryboard.Children.Add(zAnimation);

            cameraPositionStoryboard.Begin();
        }
        #endregion
        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");
            worldMatrix = Matrix.Identity;

            viewMatrix = Matrix.CreateLookAt(CameraPosition, new Vector3(0.0f, 0.0f, 0.0f), v3CamUp);
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.AspectRatio, 1.0f, 100.0f);
            AnimateCameraPosition(new Vector3(2.0f, 3.0f, 10.0f));
            // Start the timer
            timer.Start();

            //Theme Color abfragen
            System.Windows.Media.Color themeColor = (System.Windows.Media.Color)System.Windows.Application.Current.Resources["PhoneBackgroundColor"];
            clrBackground = new Color(themeColor.R, themeColor.G, themeColor.B, themeColor.A);
            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)
        {
            viewMatrix = Matrix.CreateLookAt(CameraPosition, new Vector3(0.0f, 0.0f, 0.0f), v3CamUp);
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(clrBackground);
            foreach (ModelMesh m in myCube.Meshes)
            {
                foreach (BasicEffect effect in m.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = worldMatrix;
                    effect.View = viewMatrix;
                    effect.Projection = projectionMatrix;
                }
                m.Draw();
            }

            uiRenderer.Render();
            // Draw the sprite
            spriteBatch.Begin();
            spriteBatch.Draw(uiRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();
        }

        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);
        }

        private void buttonOben_Click(object sender, RoutedEventArgs e)
        {
            AnimateCameraPosition(new Vector3(0.0f, 10.0f, 0.0f));
            v3CamUp = Vector3.Backward;
        }

        private void Unten_Click(object sender, RoutedEventArgs e)
        {
            AnimateCameraPosition(new Vector3(0.0f, -10.0f, 0.0f));
            v3CamUp = Vector3.Forward;
        }

        private void Vorne_Click(object sender, RoutedEventArgs e)
        {
            AnimateCameraPosition(new Vector3(0.0f, 0.0f, 10.0f));
            v3CamUp = Vector3.Up;
        }

        private void Hinten_Click(object sender, RoutedEventArgs e)
        {
            AnimateCameraPosition(new Vector3(0.0f, 0.0f, -10.0f));
            v3CamUp = Vector3.Up;
        }

        private void Links_Click(object sender, RoutedEventArgs e)
        {
            AnimateCameraPosition(new Vector3(-10.0f, 0.0f, 0.0f));
            v3CamUp = Vector3.Up;
        }

        private void Rechts_Click(object sender, RoutedEventArgs e)
        {
            AnimateCameraPosition(new Vector3(10.0f, 0.0f, 0.0f));
            v3CamUp = Vector3.Up;
        }

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            AnimateCameraPosition(new Vector3(2.0f, 3.0f, 10.0f));
            v3CamUp = Vector3.Up;
        }
    }
}