using ControlExplorer.Common;
using ControlExplorer.Data;
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.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;

// The Split Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234234

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 SamplePage : 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 SamplePage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
            
            comboThemes.ItemsSource = new string[] { ElementTheme.Light.ToString(), ElementTheme.Dark.ToString() };

            this.Loaded += PageLoaded;
            this.Unloaded += PageUnloaded;
        }

        private void PageUnloaded(object sender, RoutedEventArgs e)
        {
            Window.Current.SizeChanged -= Window_SizeChanged;
        }

        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)
        {
            string demoTypeName = "";

            var control = e.NavigationParameter as ControlDescription;
            if (control == null)
            {
                var newFeature = e.NavigationParameter as NewFeatureDescription;
                if (newFeature != null)
                {
                    control = MainViewModel.Instance.GetControl(newFeature.ControlName);
                    demoTypeName = newFeature.DemoControlTypeName;
                }
            }

            if (control != null)
            {
                this.DefaultViewModel["Control"] = control;
                this.DefaultViewModel["Samples"] = control.GetAllFeatures().ToList();

                if (!string.IsNullOrEmpty(demoTypeName))
                {
                    //itemListView.SelectedItem = control.GetFeature(demoTypeName);
                    this.itemsViewSource.View.MoveCurrentTo(control.GetFeature(demoTypeName));
                }
                else
                {
                    if (e.PageState != null && e.PageState.ContainsKey("currentPosition"))
                    {
                        this.itemsViewSource.View.MoveCurrentTo(this.itemsViewSource.View[(int)e.PageState["currentPosition"]]);
                    }
                    else
                    {
                        this.itemsViewSource.View.MoveCurrentToFirst();
                        // Select the first item automatically unless logical page navigation is being used
                        // (see the logical page navigation #region below.)
                        //if (!this.UsingLogicalPageNavigation()) this.itemsViewSource.View.MoveCurrentToFirst();
                    }
                }
            }
        }

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

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property provides the control to be displayed.</param>
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
            
            
        //}

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

        /// <summary>
        /// Invoked when an item within the list is selected.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is Snapped)
        /// displaying the selected item.</param>
        /// <param name="e">Event data that describes how the selection was changed.</param>
        void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Invalidate the view state when logical page navigation is in effect, as a change
            // in selection may cause a corresponding change in the current logical page.  When
            // an item is selected this has the effect of changing from displaying the item list
            // to showing the selected item's details.  When the selection is cleared this has the
            // opposite effect.
           // if (this.UsingLogicalPageNavigation()) this.InvalidateVisualState();
            if (e.AddedItems.Count < 1) return;

            var currentFeature = e.AddedItems[0] as FeatureDescription;
            comboThemes.SelectedItem = SampleFrame.RequestedTheme == ElementTheme.Light || SampleFrame.RequestedTheme == ElementTheme.Default || !currentFeature.SupportThemes ? "Light" : "Dark";

            // clear app bar buttons
            bottomAppBar.Content = null;
            bottomAppBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }

        /// <summary>
        /// Invoked when the page's back button is pressed.
        /// </summary>
        /// <param name="sender">The back button instance.</param>
        /// <param name="e">Event data that describes how the back button was clicked.</param>
        //protected override void GoBack(object sender, RoutedEventArgs e)
        //{
        //    if (this.UsingLogicalPageNavigation() && itemListView.SelectedItem != null)
        //    {
        //        // When logical page navigation is in effect and there's a selected item that
        //        // item's details are currently displayed.  Clearing the selection will return
        //        // to the item list.  From the user's point of view this is a logical backward
        //        // navigation.
        //        this.itemListView.SelectedItem = null;
        //    }
        //    else
        //    {
        //        // When logical page navigation is not in effect, or when there is no selected
        //        // item, use the default back button behavior.
        //        base.GoBack(sender, e);
        //    }
        //}

        /// <summary>
        /// Invoked to determine the name of the visual state that corresponds to an application
        /// view state.
        /// </summary>
        /// <param name="viewState">The view state for which the question is being posed.</param>
        /// <returns>The name of the desired visual state.  This is the same as the name of the
        /// view state except when there is a selected item in portrait and snapped views where
        /// this additional logical page is represented by adding a suffix of _Detail.</returns>
        //protected override string DetermineVisualState(ApplicationViewState viewState)
        //{
        //    // Update the back button's enabled state when the view state changes
        //    var logicalPageBack = this.UsingLogicalPageNavigation(viewState) && this.itemListView.SelectedItem != null;
        //    var physicalPageBack = this.Frame != null && this.Frame.CanGoBack;
        //    this.DefaultViewModel["CanGoBack"] = logicalPageBack || physicalPageBack;

        //    // Start with the default visual state name, and add a suffix when logical page
        //    // navigation is in effect and we need to display details instead of the list
        //    var defaultStateName = base.DetermineVisualState(viewState);
        //    return logicalPageBack ? defaultStateName + "_Detail" : defaultStateName;
        //}

        #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 comboThemes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var theme = (ElementTheme)Enum.Parse(typeof(ElementTheme), comboThemes.SelectedItem as string);
            SampleFrame.RequestedTheme = theme;
        }

        private void btnSource_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(SourceCodePage), this.itemsViewSource.View.CurrentItem);
        }
    }
}
