﻿namespace CSharpPro.Delegation
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  class RunDelegation
  {
    private delegate decimal DecimalOp(decimal value);

    private static readonly DecimalOp[] DecimalOps = { MathOperation.MultiByTwo, MathOperation.Square };

    public static void RunOp()
    {
      Console.WriteLine("Delegation math op");
      DecimalOps.ToList().ForEach(_ => Console.WriteLine(_(3m)));

      //func
      DisplayResults(MathOperation.MultiByTwo, 3m);
      DisplayResults(MathOperation.Square, 3m);

      //action
      ActionDisplay(ActionExample.Action0, "c#");
      ActionDisplay(ActionExample.Action1, "guys");

      //bubble sort
      BubbleSort();

      //multi case stop
      MultiCastStop();

      //multi cast non stop
      MultiCastNonStop();
    }

    private static void DisplayResults(Func<decimal, decimal> func, decimal value)
    {
      Console.WriteLine(func(value));
    }

    //no resturns for action
    private static void ActionDisplay(Action<string> action, string value)
    {
      try
      {
        action(value);
      }
      catch (Exception)
      {
       Console.WriteLine("action test exception!");
      }
      
    }

    //buble sort
    private static void BubbleSort()
    {
      var employees = new List<Employee>
                        {
                          new Employee("tom",30m),
                          new Employee("david",12),
                          new Employee("jack",23)
                        };
      BubbleSorter.Sort(employees, Employee.CompareEmployee);
      employees.ForEach(Console.WriteLine);
    }

    //multi cast delegation
    private static void MultiCastStop()
    {
      Action<string> actions = ActionExample.Action0;
      actions += ActionExample.Action1;

      try
      {
        actions("c#");
      }
      catch (Exception)
      {
        Console.WriteLine("multi cast stop exception occured!");
      }
    }

    //multi cast delegation
    private static void MultiCastNonStop()
    {
      Action<string> actions = ActionExample.Action0;
      actions += ActionExample.Action1;
      Delegate[] delegates = actions.GetInvocationList();

      foreach (var item in delegates)
      {
        var action = (Action<string>)item;
        try
        {
          action("c#");
        }
        catch (Exception)
        {
          Console.WriteLine("multi cast non stop exception occured!");
        }
      }
    }
  }
}
