using System;
using System.Collections.Generic;
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;
using System.IO;

namespace AsynchroneAusfuehrung
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //// Befehle für Datei-Menü in eime Zug mit Handlern verbinden und registrieren
            //CommandBindings.Add(new CommandBinding(ApplicationCommands.Open,
            //                                       miFileOpen_Handler));
            //CommandBindings.Add(new CommandBinding(ApplicationCommands.Close,
            //                                       miFileQuit_Handler));

            //// Befehle für Datei-Menü mit Menüelementen verbinden
            //miFileOpen.Command = ApplicationCommands.Open;
            //miFileQuit.Command = ApplicationCommands.Close;


        }


        //// Ereignisbehandlungsmethoden für Menübefehle
        //void miFileOpen_Handler(object sender, ExecutedRoutedEventArgs args)
        //{
        //    statusLabel.Content = statusLabel.Content + " miFileOpen1 ";
        //    //Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
        //    //openFileDialog.DefaultExt = ".txt";
        //    //openFileDialog.Filter = "Textdateien (*.txt)|*.txt";

        //    //if (openFileDialog.ShowDialog() == true)
        //    //{
        //    //    // Dateiinhalt einlesen
        //    //    //await open(openFileDialog.FileName);
        //    //}
        //    ProcessRead();


        //    statusLabel.Content = statusLabel.Content + " miFileOpen2 ";
        //}

        //public async void ProcessRead()
        //{
        //    string filePath = @"d:\temp\datei3.txt";

        //    if (File.Exists(filePath) == false)
        //    {
        //        Console.WriteLine("file not found: " + filePath);
        //    }
        //    else
        //    {
        //        try
        //        {
        //            string text = await ReadTextAsync(filePath);
        //            textBox1.Text = text;
        //            Console.WriteLine(text);
        //        }
        //        catch (Exception ex)
        //        {
        //            Console.WriteLine(ex.Message);
        //        }
        //    }
        //}

        //private async Task<string> ReadTextAsync(string filePath)
        //{
        //    using (FileStream sourceStream = new FileStream(filePath,
        //        FileMode.Open, FileAccess.Read, FileShare.Read,
        //        bufferSize: 4096, useAsync: true))
        //    {
        //        StringBuilder sb = new StringBuilder();

        //        byte[] buffer = new byte[0x1000];
        //        int numRead;
        //        while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
        //        {
        //            string text = Encoding.Unicode.GetString(buffer, 0, numRead);
        //            sb.Append(text);
        //        }

        //        return sb.ToString();
        //    }
        //}




        //private async Task open(string filename)
        //{
        //    statusLabel.Content = statusLabel.Content + " open1 ";
        //    await openAsync(filename);
        //    statusLabel.Content = statusLabel.Content + " open2 ";
        //}
        //private async Task<string> openAsync(string filename)
        //{
        //    statusLabel.Content = statusLabel.Content + " openAsync1 ";
        //    try
        //    {
        //        StreamReader sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None, 4096, true),
        //                                           Encoding.GetEncoding("windows-1252"), true);
        //        textBox1.Text = await sr.ReadToEndAsync();
        //        sr.Close();
        //    }
        //    catch (IOException)
        //    {
        //        MessageBox.Show("Datei konnte nicht geöffnet werden.", "Fehler");
        //    }

        //    statusLabel.Content = statusLabel.Content + " openAsync2 ";
        //    return textBox1.Text;
        //}
        ////private async string openAsync(string filename)
        ////{
        ////    label1.Content = label1.Content + " openAsync1 ";
        ////    try
        ////    {
        ////        StreamReader sr = new StreamReader(filename,
        ////                                           Encoding.GetEncoding("windows-1252"), true);
        ////        textBox1.Text = await sr.ReadToEndAsync();
        ////        sr.Close();
        ////    }
        ////    catch (IOException)
        ////    {
        ////        MessageBox.Show("Datei konnte nicht geöffnet werden.", "Fehler");
        ////    }

        ////    label1.Content = label1.Content + " openAsync2 ";
        ////    return textBox1.Text;
        ////}



        //void miFileQuit_Handler(object sender, ExecutedRoutedEventArgs args)
        //{
        //    this.Close();
        //}



        //private async void Button_Click_1(object sender, RoutedEventArgs e)
        //{
        //    //label1.Content = label1.Content + " button1 ";
        //    //Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
        //    //openFileDialog.DefaultExt = ".txt";
        //    //openFileDialog.Filter = "Textdateien (*.txt)|*.txt";

        //    //if (openFileDialog.ShowDialog() == true)
        //    //{
        //    //    // Dateiinhalt einlesen
        //    //    await openLineAsync(openFileDialog.FileName);
        //    //}

        //    //label1.Content = label1.Content + " button2 ";
        //    string UserDirectory = @"c:\temp\";

        //    using (StreamReader SourceReader = File.OpenText(UserDirectory + "Kopieren.iso"))
        //    {
        //        using (StreamWriter DestinationWriter = File.CreateText(UserDirectory + "CopiedFile.txt"))
        //        {
        //            await CopyFilesAsync(SourceReader, DestinationWriter);
        //        }
        //    }
        //}

        //public async Task CopyFilesAsync(StreamReader Source, StreamWriter Destination)
        //{
        //    char[] buffer = new char[0x10];
        //    int numRead;
        //    while ((numRead = await Source.ReadAsync(buffer, 0, buffer.Length)) != 0)
        //    {
        //        await Destination.WriteAsync(buffer, 0, numRead);
        //    }
        //}





















        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            statusLabel.Content = "Berechnung gestartet";

            int value;

            for (int n = 0; n < 10; n++)
            {
                value = calculate();
                //value = await calculateAsync();
                textBox1.Text = value.ToString();
            }

            statusLabel.Content = "Berechnung beendet";
        }


        //async Task DoWorkAsync()
        //{
        //    int value;

        //    for (int n = 0; n < 10; n++)
        //    {
        //        value = calculate();
        //        //value = await calculateAsync();
        //        textBox1.Text = value.ToString();
        //    }
        //}

        //void DoWork()
        //{
        //    int value;

        //    for (int n = 0; n < 10; n++)
        //    {
        //        value = calculate();
        //        textBox1.Text = value.ToString();
        //    }
        //}



        public async Task<int> calculateAsync()
        {
            if (SynchronizationContext.Current != null)
                textBlock1.Text = SynchronizationContext.Current.ToString();
            var result = (int) await Task.Run(() =>
            {
                Thread.Sleep(1000);
                Random gen = new Random();
                if (SynchronizationContext.Current != null)
                    textBlock2.Text = SynchronizationContext.Current.ToString();
                return gen.Next(10);
            });

            //Thread.Sleep(1000);
            //Random gen = new Random();
            //return gen.Next(10);

            return result;
        }


        public int calculate()
        {
            if (SynchronizationContext.Current != null)
                textBox1.Text = SynchronizationContext.Current.ToString();
            var result = Task.Run(() =>
            {
                Thread.Sleep(1000);
                Random gen = new Random();
                if (SynchronizationContext.Current != null)
                    textBlock2.Text = SynchronizationContext.Current.ToString();
                return gen.Next(10);
            });
            return result.Result;

            //Thread.Sleep(1000);
            //Random gen = new Random();
            //return gen.Next(10);

        }


    }
}
