using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Navigation;
using FirstWP8App.ViewModels;
using Microsoft.Phone.Controls;
using Windows.Phone.Speech.Synthesis;
using Windows.Phone.System.UserProfile;

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

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

		// When page is navigated to set data context to selected item in list
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			if (DataContext == null)
			{
				string selectedIndex;
				if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
				{
					int index = int.Parse(selectedIndex);
					DataContext = App.ViewModel.Items[index];
				}
			}
		}

		private async void Read_Click(object sender, EventArgs e)
		{
			// speak the description text
			SpeechSynthesizer speechSynth = new SpeechSynthesizer();
			await speechSynth.SpeakTextAsync((DataContext as ItemViewModel).LineOne);
		}

		private async void Lock_Click(object sender, EventArgs e)
		{
			// prompt the user to allow setting the lock screen wallpaper
			if (!LockScreenManager.IsProvidedByCurrentApplication)
			{
				LockScreenRequestResult result = await LockScreenManager.RequestAccessAsync();
				if (result == LockScreenRequestResult.Granted)
					SetWallpaper();
			}
			else
				SetWallpaper();
		}

		private async Task SetWallpaper()
		{
			// download the image
			WebClient wc = new WebClient();
			Stream s = await wc.DownloadStreamTask((DataContext as ItemViewModel).ImageUri);

			Uri current = null;

			// grab the current image Uri
			try
			{
				current = LockScreen.GetImageUri();
			}
			catch
			{
			}

			// create a new, unique filename
			string name = Guid.NewGuid().ToString();

			// open that file in isolated storage
			IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
			IsolatedStorageFileStream stream = file.CreateFile(name);

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

			// set the lock screen to the new image
			LockScreen.SetImageUri(new Uri("ms-appdata:///Local/" + name, UriKind.RelativeOrAbsolute));

			// delete the old image
			if(current != null)
				file.DeleteFile(current.Segments[2]);
		}

		// 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);
		//}
	}
}