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 Examples18_19
    {
        // Kod umieszczony w komentarzu gdyż pokazuje rozwiązanie, którego nie należy stosować.
        // Listing 18-18
        //public async Task<string> FindLongestLineAsync(string url)
        //{
        //    if (url == null)
        //    {
        //        throw new ArgumentNullException("url");
        //    }
        //    ...
        //}

        // Listing 18-19
        public Task<string> FindLongestLineAsync(string url)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }
            return FindLongestLineCore(url);
        }

        private async Task<string> FindLongestLineCore(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;
                }
            }
        }
    }
}
