using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Contexts
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // Listing 17-8
        private void fetchButton_Click(object sender, RoutedEventArgs e)
        {
            SynchronizationContext uiContext = SynchronizationContext.Current;

            Task.Factory.StartNew(() =>
            {
                string pictures =
                    Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                var folder = new DirectoryInfo(pictures);
                FileInfo[] allFiles =
                    folder.GetFiles("*.jpg", SearchOption.AllDirectories);
                FileInfo largest =
                    allFiles.OrderByDescending(f => f.Length).FirstOrDefault();

                uiContext.Post(unusedArg =>
                {
                    outputTextBox.Text = string.Format("Największym plikiem ({0}MB) jest {1}",
                        largest.Length / (1024 * 1024), largest.FullName);
                },
                null);
            });
        }
    }
}
