using System;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using FirstUniversalApp.ViewModels;
#if WINDOWS_PHONE_APP
using Windows.Media.SpeechRecognition;
#endif

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

namespace FirstUniversalApp
{
	/// <summary>
	/// An empty page that can be used on its own or navigated to within a Frame.
	/// </summary>
	public sealed partial class MainPage : Page
	{
		public MainPage()
		{
			this.InitializeComponent();

			DataContext = App.ViewModel;

			this.NavigationCacheMode = NavigationCacheMode.Required;
		}

		/// <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.
		/// This parameter is typically used to configure the page.</param>
		protected override async void OnNavigatedTo(NavigationEventArgs e)
		{
			if (e.NavigationMode == NavigationMode.New)
			{
#if WINDOWS_PHONE_APP
				StorageFile storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///VCD.xml"));
				await VoiceCommandManager.InstallCommandSetsFromStorageFileAsync(storageFile);
#endif
			}

			// TODO: If your application contains multiple pages, ensure that you are
			// handling the hardware Back button by registering for the
			// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
			// If you are using the NavigationHelper provided by some templates,
			// this event is handled for you.
		}

		private void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			// If selected item is null (no selection) do nothing
			if (MainLongListSelector.SelectedItem == null)
				return;

			Frame.Navigate(typeof(DetailsPage), (MainLongListSelector.SelectedItem as ItemViewModel).Id);

			// Reset selected item to null (no selection)
			MainLongListSelector.SelectedItem = null;
		}

		private async void Refresh_Click(object sender, RoutedEventArgs e)
		{
			await App.ViewModel.LoadData();
		}

		private async void Speak_Click(object sender, RoutedEventArgs e)
		{
#if WINDOWS_PHONE_APP
			SpeechRecognizer sr = new SpeechRecognizer();
			await sr.CompileConstraintsAsync();
			SpeechRecognitionResult result = await sr.RecognizeWithUIAsync();
			if(result.Confidence == SpeechRecognitionConfidence.High || result.Confidence == SpeechRecognitionConfidence.Medium)
				await App.ViewModel.LoadData(result.Text);
#else
			await new MessageDialog("Not supported!").ShowAsync();
#endif
		}
	}
}
