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

namespace ControlExplorer
{
    public partial class SampleListPage : Page
    {
        private int _controlIndex;
        public SampleListPage()
        {
            InitializeComponent();
            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;
            }
        }

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

            var parameters = (NavigationParameters)e.Parameter;
            _controlIndex = parameters.ControlId;
            DataContext = ViewModel.Instance.Controls[parameters.ControlId];

            LoadTransition.Begin();
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
            DataContext = null;
        }

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

        void SelectionTransition_Completed(object sender, object e)
        {
            list.IsEnabled = true;
            Frame.Navigate(typeof(SamplePage), new NavigationParameters { ControlId = _controlIndex, SampleIndex = list.SelectedIndex });
        }
    }
}