using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nativ;
using System.Windows.Media;
using System.Drawing;
using System.Windows.Interop;
using System.Windows;
using System.Windows.Media.Imaging;
using TwoCamWPF.Settings;
using System.Reflection;

namespace TwoCamWPF.Helpers
{
    static class Extentions
    {
        public static void ForEach<T>(this IEnumerable<T> lst, Action<T> function)
        {
            foreach (T item in lst)
            {
                try
                {
                    function(item);
                }
                catch (Exception ex)
                {
                    Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), "Ошибка в Extentions ");
                    Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), "Функция " + function.Target);
                    Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), "Метод " + function.Method.Name);

                    Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), ex.Message);
                    
                }
            }
        }

        public static T FirstOrDefault<T>(this IEnumerable<T> lst, Func<T, bool> predicate, T defaultValue)
        {
            T result = lst.FirstOrDefault(predicate);
            if (result == null)
                return defaultValue;
            else
                return result;
        }

       
    }

    public static class BitmapExtensions
    {
        public static ImageSource ToImageSource(this Bitmap bitmap)
        {
            lock (bitmap)
            {
                IntPtr hbitmap = bitmap.GetHbitmap();
                try
                {
                    ImageSource imageSource = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bitmap.Width, bitmap.Height));
                    return imageSource;
                }
                finally
                {
                    NativeMethods.DeleteObject(hbitmap);
                }
            }
        }
    }
}
