using System;
using Windows.Phone.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;

namespace ControlExplorer
{
    public partial class MainPage : Page
    {
        GridView _lastlist;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            DataContext = ViewModel.Instance;

            SelectionTransition.Completed += SelectionTransition_Completed;
            Loaded += OnLoaded;
            Unloaded += OnUnloaded;
        }

        void OnLoaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            HardwareButtons.BackPressed += OnBackPressed;
        }

        void OnUnloaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            HardwareButtons.BackPressed -= OnBackPressed;
        }
        
        private void OnBackPressed(object sender, BackPressedEventArgs e)
        {
            if (Frame.CanGoBack)
            {
                Frame.GoBack();
                e.Handled = true;
            }
        }

        private void OnItemSelected(object sender, SelectionChangedEventArgs e)
        {
            _lastlist = (GridView)sender;
            if (_lastlist.SelectedIndex != -1)
            {
                SelectionTransition.Begin();
                _lastlist.IsEnabled = false;
            }
        }

        void SelectionTransition_Completed(object sender, object e)
        {
            _lastlist.IsEnabled = true;
            var control = (ControlViewModel)_lastlist.SelectedItem;
            var controlIndex = ViewModel.Instance.Controls.IndexOf(control);
            if (control.Samples.Count == 1)
            {
                Frame.Navigate(typeof(SamplePage), new NavigationParameters { ControlId = controlIndex });
            }
            else
            {
                Frame.Navigate(typeof(SampleListPage), new NavigationParameters { ControlId = controlIndex });
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (_lastlist != null)
            {
                _lastlist.SelectedIndex = -1;
            }

            LoadTransition.Begin();
        }

        private void OnSettingsClick(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(SettingsPage));
        }

        private void OnAboutClick(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(AboutPage));
        }
    }
}