using ControlExplorer.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.Phone.UI.Input;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace ControlExplorer
{
    /// <summary>
    /// A page that displays a control title, a list of items within the control, and details for the
    /// currently selected item.
    /// </summary>
    public sealed partial class ItemDetailPage : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        public ItemDetailPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
            this.Loaded += PageLoaded;
        }
        private void PageLoaded(object sender, RoutedEventArgs e)
        {
            Window.Current.SizeChanged += Window_SizeChanged;
        }

        private void Window_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
        {
            if (e.Size.Width <= 700)
            {
                VisualStateManager.GoToState(this, "Snapped", false);
            }
            else if (e.Size.Height > e.Size.Width)
            {
                //VisualStateManager.GoToState(this, "FullScreenPortrait", true);
            }
            else
            {
                VisualStateManager.GoToState(this, "FullScreenLandscape", false);
            }
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var description = e.NavigationParameter as FeatureDescription;
            var control = description.Control;
            if (control != null)
            {
                this.DefaultViewModel["Control"] = control;
                this.DefaultViewModel["Samples"] = control.GetAllFeatures().ToList();
                if (flipView != null)
                {
                    flipView.SelectedItem = description;
                }
            }
        }

        void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            e.PageState.Add("currentPosition", this.itemsViewSource.View.CurrentPosition);
        }

        #region Logical page navigation

        // Visual state management typically reflects the four application view states directly
        // (full screen landscape and portrait plus snapped and filled views.)  The split page is
        // designed so that the snapped and portrait view states each have two distinct sub-states:
        // either the item list or the details are displayed, but not both at the same time.
        //
        // This is all implemented with a single physical page that can represent two logical
        // pages.  The code below achieves this goal without making the user aware of the
        // distinction.

        /// <summary>
        /// Invoked to determine whether the page should act as one logical page or two.
        /// </summary>
        /// <param name="viewState">The view state for which the question is being posed, or null
        /// for the current view state.  This parameter is optional with null as the default
        /// value.</param>
        /// <returns>True when the view state in question is portrait or snapped, false
        /// otherwise.</returns>
        private bool UsingLogicalPageNavigation(ApplicationView viewState = null)
        {
            //if (viewState == null) viewState = ApplicationView.GetForCurrentView();
            return false;
            //return Window.Current.Bounds.
            //if (viewState == null) viewState = ApplicationView.Value;
            //return viewState == ApplicationViewState.FullScreenPortrait ||
            //    viewState == ApplicationViewState.Snapped;
        }

        #endregion

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        private void flipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var description = (this.flipView.SelectedItem as FeatureDescription).Description;


            if (heights.ContainsKey(description))
            {
                row1.Height = new GridLength(heights[description]);
            }
            else
            {
                var container = this.flipView.ContainerFromIndex(this.flipView.SelectedIndex);
                if (container != null && container is FlipViewItem)
                {
                    var fi = container as FlipViewItem;
                    var tb = fi.ContentTemplateRoot as TextBlock;
                    if (tb != null)
                    {
                        row1.Height = new GridLength(tb.ActualHeight);
                        heights[description] = tb.ActualHeight;
                    }
                }
            }
        }


        Dictionary<string, double> heights = new Dictionary<string, double>();
        private void tb_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var description = (this.flipView.SelectedItem as FeatureDescription).Description;
            var tb = sender as TextBlock;

            heights[tb.Text] = tb.ActualHeight;
            if (tb.Text==description)
            {
                row1.Height = new GridLength(tb.ActualHeight);
            }
        }

    }
}
