using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Errors
{
    class Example16_17
    {
        // Listing 18-16
        private static async Task<string> FindLongestLineAsync(string url)
        {
            using (var w = new HttpClient())
            {
                Stream body = await w.GetStreamAsync(url);
                using (var bodyTextReader = new StreamReader(body))
                {
                    string longestLine = string.Empty;
                    while (!bodyTextReader.EndOfStream)
                    {
                        string line = await bodyTextReader.ReadLineAsync();
                        if (longestLine.Length > line.Length)
                        {
                            longestLine = line;
                        }
                    }
                    return longestLine;
                }
            }
        }

        public static async Task HandleAsyncException()
        {
            // Listing 18-17
            try
            {
                string longest = await FindLongestLineAsync("http://192.168.22.1/");
                Console.WriteLine("Najdłuższy wiersz: " + longest);
            }
            catch (HttpRequestException x)
            {
                Console.WriteLine("Błąd podczas pobierania strony: " + x.Message);
            }

        }
    }
}
