namespace Exceptions;

class Program
{
    static void Main(string[] args)
    {
        using (var r = new StreamReader(@"C:\Temp\File.txt"))
        {
            while (!r.EndOfStream)
            {
                Console.WriteLine(r.ReadLine());
            }
        }
    }

    static int Divide(int x, int y)
    {
        return x / y;
    }

    static void HandlingExceptions()
    {
        try
        {
            using (var r = new StreamReader(@"C:\Temp\File.txt"))
            {
                while (!r.EndOfStream)
                {
                    Console.WriteLine(r.ReadLine());
                }
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Nie można znaleźć pliku!");
        }
    }

    static void ExceptionObjects()
    {
        try
        {
            // ... ten sam kod co na listingu 8-3 ...
            using (var r = new StreamReader(@"C:\Temp\File.txt"))
            {
                while (!r.EndOfStream)
                {
                    Console.WriteLine(r.ReadLine());
                }
            }
        }
        catch (FileNotFoundException x)
        {
            Console.WriteLine($"Brak pliku '{x.FileName}'!");
        }
    }

    static void MultipleCatchBlocks()
    {
        try
        {
            using (var r = new StreamReader(@"C:\Temp\File.txt"))
            {
                while (!r.EndOfStream)
                {
                    Console.WriteLine(r.ReadLine());
                }
            }
        }
        catch (FileNotFoundException x)
        {
            Console.WriteLine($"Nie udało się odnaleźć pliku '{x.FileName}'");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine($"Nie znaleziono katalogu zawierającego plik.");
        }
        catch (IOException x)
        {
            Console.WriteLine($"Błąd wejścia-wyjścia: '{x.Message}'");
        }
    }

    public static bool InsertIfDoesNotExist(MyEntity item, TableClient table)
    {
        try
        {
            table.AddEntity(item);
            return true;
        }
        catch (RequestFailedException x)
        when (x.Status == 409)
        {
            return false;
        }
    }

    public static string GetCommaSeparatedEntry(string text, int position)
    {
        string[] parts = text.Split(',');
        if (position < 0 || position >= parts.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(position));
        }
        return parts[position];
    }

    public static int CountCommas(string text)
    {
        ArgumentNullException.ThrowIfNull(text);
        return text.Count(ch => ch == ',');
    }
}
