namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_12
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using AddisonWesley.Michaelis.EssentialCSharp.Shared;

    public class Program
    {
        public static void Main()
        {
            string stars =
                "*".PadRight(Console.WindowWidth - 1, '*');
            Console.WriteLine("Wciśnij ENTER, aby zakończyć.");

            CancellationTokenSource cancellationTokenSource =
                new CancellationTokenSource();

            // Aby zastosować bibliotekę TPL w wersjach starszych niż .NET 4.5, 
            // wywołaj metodę Task.Factory.StartNew<string>().
            Task task = Task.Factory.StartNew(
                () =>
                    WritePi(cancellationTokenSource.Token),
                        TaskCreationOptions.LongRunning);

            // Oczekiwanie na dane wejściowe od użytkownika
            Console.ReadLine();

            cancellationTokenSource.Cancel();
            Console.WriteLine(stars);
            task.Wait();
            Console.WriteLine();
        }

        private static void WritePi(
            CancellationToken cancellationToken)
        {
            const int batchSize = 1;
            string piSection = string.Empty;
            int i = 0;

            while(!cancellationToken.IsCancellationRequested
                || i == int.MaxValue)
            {
                piSection = PiCalculator.Calculate(
                    batchSize, (i++) * batchSize);
                Console.Write(piSection);
            }
        }
    }
}

