using System.Diagnostics;
using System.Reactive;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
using static System.Runtime.CompilerServices.MethodImplOptions;

namespace InnovEnergy.Lib.Protocols.DBus.Utils;

internal static class Extensions
{
    
    // this is a copy of a method in Utils
    // it is reimplemented here in order to make this project independent of Utils
    [DebuggerStepThrough][MethodImpl(AggressiveInlining | AggressiveOptimization)]
    public static R Apply<T, R>(this T t, Func<T, R> f) => f(t);

    // this is a copy of a method in Utils
    // it is reimplemented here in order to make this project independent of Utils
    public static Boolean IsNullOrEmpty(this String? s) => String.IsNullOrEmpty(s);
    
    public static IObservable<TSource> DumpErrors<TSource>(this IObservable<TSource> source)
    {
        return source.DoOnError(Console.WriteLine);
    }
    
    public static IObservable<TSource> DoOnError<TSource>(this IObservable<TSource> source, Action<Exception> action )
    {
        return source
              .Materialize()
              .Do(n =>
              {
                  if (n.Kind == NotificationKind.OnError)
                      action(n.Exception!);
              })
              .Dematerialize();
    }

}