using ControlExplorer.Common;
using ControlExplorer.UserControls;
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.ApplicationSettings;
using Windows.UI.Popups;
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 Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234233

namespace ControlExplorer
{
    /// <summary>
    /// A page that displays a collection of item previews.  In the Split Application this page
    /// is used to display and select one of the available groups.
    /// </summary>
    public sealed partial class HomePage : 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 HomePage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.Loaded += HomePage_Loaded;
        }

        /// <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)
        {
            MainViewModel mvm = e.NavigationParameter as MainViewModel;
            await mvm.Load();
            //this.DefaultViewModel["Items"] = mvm.Controls;
            this.DefaultViewModel["NewFeatures"] = mvm.NewFeatures;
            this.DefaultViewModel["Favorites"] = mvm.Controls.Where(c => c.IsFavorite);
        }

        void HomePage_Loaded(object sender, RoutedEventArgs e)
        {
 	        SettingsPane.GetForCurrentView().CommandsRequested += HomePage_CommandsRequested;
        }

        private Guid privacyId = new Guid("{997BAFCE-773F-473C-B9CA-F99C98DF2946}");
        void HomePage_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            SettingsCommand privacyCommand = new SettingsCommand(privacyId, "Privacy",
               (handler) =>
               {
                   PrivacySettingsFlyout sf = new PrivacySettingsFlyout();
                   sf.Show();
               });
            args.Request.ApplicationCommands.Add(privacyCommand);
        }

        /// <summary>
        /// Invoked when an item is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            if((e.ClickedItem as ControlDescription).Name.Equals("See All"))
            {
                this.Frame.Navigate(typeof(ControlsPage), MainViewModel.Instance);
            }
            else
            { 
                this.Frame.Navigate(typeof(SamplePage), e.ClickedItem);
            }
        }

        private void newFeaturesGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Frame.Navigate(typeof(SamplePage), e.ClickedItem);
        }

        #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 Hub_SectionHeaderClick(object sender, HubSectionHeaderClickEventArgs e)
        {
            if(e.Section.Name.Equals("ControlsHub"))
            {
                this.Frame.Navigate(typeof(ControlsPage), MainViewModel.Instance);
            }
        }

        private void Logo_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Windows.System.Launcher.LaunchUriAsync(new Uri("http://www.componentone.com/Studio/Platform/WinRT"));
        }
    }

    public class MyStyleSelector : StyleSelector
    {
        public Style ItemContainerStyle { get; set; }

        protected override Style SelectStyleCore(object item, DependencyObject container)
        {
            var control = item as ControlDescription;
            var gvi = container as GridViewItem;
            var lvi = container as ListViewItem;
            if (gvi != null)
                gvi.IsEnabled = control.IsEnabled;
            if (lvi != null)
                lvi.IsEnabled = control.IsEnabled;
            return ItemContainerStyle;
            //return base.SelectStyleCore(item, container);
        }
    }

    /// <summary>
    /// This class sets VariableSizedWrapGrid.ColumnSpanProperty for GridViewItem controls,
    /// so that every item can have different size in the VariableSizedWrapGrid.
    /// </summary>
    public class C1GridView : GridView
    {
        // set ColumnSpan according to the business logic (maybe some GridViewSamples.Samples.Item or group properties)
        protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
        {
            try
            {
                NewFeatureDescription it = item as NewFeatureDescription;
                if (it != null)
                {  
                    element.SetValue(Windows.UI.Xaml.Controls.VariableSizedWrapGrid.ColumnSpanProperty, it.ItemSize);
                }
            }
            catch
            {
                element.SetValue(Windows.UI.Xaml.Controls.VariableSizedWrapGrid.ColumnSpanProperty, 1);
            }
            finally
            {
                base.PrepareContainerForItemOverride(element, item);
            }
        }
    }

}
