using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using FirstWP8App.ViewModels;
using Microsoft.Phone.Shell;
using Windows.Phone.Speech.Recognition;
using Windows.Phone.Speech.VoiceCommands;

namespace FirstWP8App
{
	public partial class MainPage : PhoneApplicationPage
	{
		// Constructor
		public MainPage()
		{
			InitializeComponent();

			// Set the data context of the LongListSelector control to the sample data
			DataContext = App.ViewModel;

			// Sample code to localize the ApplicationBar
			//BuildLocalizedApplicationBar();
		}

		// Load data for the ViewModel Items
		protected async override void OnNavigatedTo(NavigationEventArgs e)
		{
			// install the Voice Command Definition file
			Uri uri = new Uri("ms-appx:///VCD.xml");

			await VoiceCommandService.InstallCommandSetsFromFileAsync(uri);

			if (!App.ViewModel.IsDataLoaded)
			{
				string search = string.Empty;

				// if we're coming from the voice screen, search for the selected tag
				if(NavigationContext.QueryString.Any())
					search = NavigationContext.QueryString["tag"];

				App.ViewModel.LoadData(search);
			}
		}

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

			// Navigate to the new page
			NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + (MainLongListSelector.SelectedItem as ItemViewModel).ID, UriKind.Relative));

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

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

		private async void Speech_Click(object sender, EventArgs e)
		{
			// recognize the command and search
			SpeechRecognizerUI speechRecognizerUi = new SpeechRecognizerUI();
			speechRecognizerUi.Settings.ExampleText = "People, places";
			speechRecognizerUi.Settings.ListenText = "Search Flickr for...";
			speechRecognizerUi.Settings.ReadoutEnabled = true;
			speechRecognizerUi.Settings.ShowConfirmation = true;
			SpeechRecognitionUIResult result = await speechRecognizerUi.RecognizeWithUIAsync();
			if (result.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
				App.ViewModel.LoadData(result.RecognitionResult.Text);
		}

		private async void Tile_Click(object sender, EventArgs e)
		{
			List<Uri> uris = new List<Uri>();

			// just grab the first images to save time
			for(int i = 0; i < 2; i++)
			{
				ItemViewModel ivm = App.ViewModel.Items[i];

				WebClient wc = new WebClient();
				Stream s = await wc.DownloadStreamTask(ivm.ImageUri);

				// open that file in isolated storage
				IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
				IsolatedStorageFileStream stream = file.CreateFile("shared/shellcontent/" + ivm.ID);

				// copy the data from the web stream to the file stream and close it up
				s.CopyTo(stream);
				stream.Close();

				// use the isostore:/ notation!
				uris.Add(new Uri("isostore:/shared/shellcontent/" + i, UriKind.RelativeOrAbsolute));
			}

			// delete the current tile if it exists
			ShellTile cycleTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("MainPage"));
			if (cycleTile != null)
				cycleTile.Delete();

			// create the new tile definition
			CycleTileData ctd = new CycleTileData
			{
				Title = "First WP8 App", 
				Count = 2, 
				CycleImages = uris
			};

			// create the tile!
			ShellTile.Create(new Uri("/MainPage.xaml", UriKind.Relative), ctd, true);
		}

		// Sample code for building a localized ApplicationBar
		//private void BuildLocalizedApplicationBar()
		//{
		//    // Set the page's ApplicationBar to a new instance of ApplicationBar.
		//    ApplicationBar = new ApplicationBar();

		//    // Create a new button and set the text value to the localized string from AppResources.
		//    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
		//    appBarButton.Text = AppResources.AppBarButtonText;
		//    ApplicationBar.Buttons.Add(appBarButton);

		//    // Create a new menu item with the localized string from AppResources.
		//    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
		//    ApplicationBar.MenuItems.Add(appBarMenuItem);
		//}
	}
}