﻿#region License
//
// Copyright 2016 Nakstem
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
// More information about this project is available at:
//
//    https://github.com/Nakstem/SortByFileTime
//
#endregion

using System;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;

namespace Nakstem.DuplicateFilesSearcher.Common
{
    /// <summary>
    ///     Helper that raises events.
    /// </summary>
    public static class EventProvider
    {
        /// <summary>
        ///     Gets or sets context of synchronized invocations
        /// </summary>
        public static ISynchronizeInvoke SynchronizationContext { get; set; }

        /// <summary>
        ///     Invokes an event on the current synchronisation context
        /// </summary>
        /// <param name="theHandler">The event handler.</param>
        /// <param name="theSender">The event sender</param>
        /// <param name="theArgs">The event arguments.</param>
        public static void SynchronizedInvoke( this EventHandler theHandler, object theSender, EventArgs theArgs )
        {
            if( SynchronizationContext != null )
            {
                if( SynchronizationContext.InvokeRequired )
                {
                    SynchronizationContext.BeginInvoke( new EventHandler( theHandler ), new[] {theSender, theArgs} );
                }
                else
                {
                    theHandler?.Invoke( theSender, theArgs );
                }
            }
            else
            {
                throw new InvalidOperationException( "The SynchronizationContext has not been set." );
            }
        }

        /// <summary>
        ///     Invokes an event on the current synchronisation context
        /// </summary>
        /// <typeparam name="T">The event arguments type.</typeparam>
        /// <param name="theHandler">The event handler.</param>
        /// <param name="theSender">The event sender</param>
        /// <param name="theArgs">The event arguments.</param>
        public static void SynchronizedInvoke< T >( this EventHandler< T > theHandler, object theSender, T theArgs )
            where T : EventArgs
        {
            if( SynchronizationContext != null )
            {
                if( SynchronizationContext.InvokeRequired )
                {
                    SynchronizationContext.BeginInvoke( new EventHandler< T >( theHandler ), new[] {theSender, theArgs} );
                }
                else
                {
                    theHandler?.Invoke( theSender, theArgs );
                }
            }
            else
            {
                throw new InvalidOperationException( "The SynchronizationContext has not been set." );
            }
        }

        /// <summary>
        ///     Invokes an action to be performed.
        /// </summary>
        /// <typeparam name="T">The action argument type.</typeparam>
        /// <param name="theHandler">The event handler.</param>
        /// <param name="theArguments">The event arguments</param>
        public static void SynchronizedInvoke< T >( this Action< T > theHandler, T theArguments )
        {
            if( SynchronizationContext != null )
            {
                if( SynchronizationContext.InvokeRequired )
                {
                    SynchronizationContext.BeginInvoke( new Action< T >( theHandler ), new object[] {theArguments} );
                }
                else
                {
                    theHandler?.Invoke( theArguments );
                }
            }
            else
            {
                throw new InvalidOperationException( "The SynchronizationContext has not been set." );
            }
        }

        /// <summary>
        ///     Invokes an action to be performed.
        /// </summary>
        /// <param name="theHandler">The action handler.</param>
        public static void SynchronizedInvoke( this Action theHandler )
        {
            if( SynchronizationContext != null )
            {
                if( SynchronizationContext.InvokeRequired )
                {
                    SynchronizationContext.BeginInvoke( theHandler, null );
                }
                else
                {
                    theHandler?.Invoke();
                }
            }
            else
            {
                throw new InvalidOperationException( "The SynchronizationContext has not been set." );
            }
        }

        /// <summary>
        ///     Invokes an action to be performed.
        /// </summary>
        /// <param name="theHandler">The action handler.</param>
        /// <param name="theArgument">The first argument</param>
        /// <param name="theSecondArgument">The second argument</param>
        public static void SynchronizedInvoke< T1, T2 >( this Action< T1, T2 > theHandler, T1 theArgument,
            T2 theSecondArgument )
        {
            if( SynchronizationContext != null )
            {
                if( SynchronizationContext.InvokeRequired )
                {
                    SynchronizationContext.BeginInvoke( new Action< T1, T2 >( theHandler ),
                        new object[] {theArgument, theSecondArgument} );
                }
                else
                {
                    theHandler?.Invoke( theArgument, theSecondArgument );
                }
            }
            else
            {
                throw new InvalidOperationException( "The SynchronizationContext has not been set." );
            }
        }

        /// <summary>
        ///     Invokes an action to be performed.
        /// </summary>
        /// <param name="theHandler">The action handler.</param>
        /// <param name="theArgument">The first argument</param>
        /// <param name="theSecondArgument">The second argument</param>
        /// <param name="theThirdArgument">The third argument</param>
        public static void SynchronizedInvoke< T1, T2, T3 >( this Action< T1, T2, T3 > theHandler, T1 theArgument,
            T2 theSecondArgument, T3 theThirdArgument )
        {
            if( SynchronizationContext != null )
            {
                if( SynchronizationContext.InvokeRequired )
                {
                    SynchronizationContext.BeginInvoke( new Action< T1, T2, T3 >( theHandler ),
                        new object[] {theArgument, theSecondArgument, theThirdArgument} );
                }
                else
                {
                    theHandler?.Invoke( theArgument, theSecondArgument, theThirdArgument );
                }
            }
            else
            {
                throw new InvalidOperationException( "The SynchronizationContext has not been set." );
            }
        }

        /// <summary>
        ///     Invokes an action to be performed.
        /// </summary>
        /// <param name="theHandler">The action handler.</param>
        /// <param name="theArgument">The first argument</param>
        /// <param name="theSecondArgument">The second argument</param>
        /// <param name="theThirdArgument">The third argument</param>
        /// <param name="theForthArgument">The forth argument</param>
        public static void SynchronizedInvoke<T1, T2, T3, T4>( this Action<T1, T2, T3, T4> theHandler, T1 theArgument,
            T2 theSecondArgument, T3 theThirdArgument, T4 theForthArgument )
        {
            if ( SynchronizationContext != null )
            {
                if ( SynchronizationContext.InvokeRequired )
                {
                    SynchronizationContext.BeginInvoke( new Action<T1, T2, T3,T4>( theHandler ),
                        new object[] { theArgument, theSecondArgument, theThirdArgument, theForthArgument } );
                }
                else
                {
                    theHandler?.Invoke( theArgument, theSecondArgument, theThirdArgument, theForthArgument );
                }
            }
            else
            {
                throw new InvalidOperationException( "The SynchronizationContext has not been set." );
            }
        }

        /// <summary>
        ///     Invokes an event asynchronously.
        /// </summary>
        /// <typeparam name="T">The event arguments type.</typeparam>
        /// <param name="theHandler">The event handler.</param>
        /// <param name="theSender">The sender of the event</param>
        /// <param name="theArgs">The event arguments</param>
        /// <param name="theErrorHandler">The action called if there is an error</param>
        public static void AsyncInvoke< T >( this EventHandler< T > theHandler, object theSender, T theArgs,
            Action< Exception > theErrorHandler ) where T : EventArgs
        {
            EventHandler< T > CopyHandler = theHandler;
            if( CopyHandler != null )
            {
                Delegate[] EventHandlers = CopyHandler.GetInvocationList();
                foreach( Delegate Handler in EventHandlers )
                {
                    ( (EventHandler< T >)Handler ).BeginInvoke( theSender, theArgs, OnEventCalled< T >, theErrorHandler );
                }
            }
        }

        /// <summary>
        ///     Method called when the event has been invoked.
        /// </summary>
        /// <param name="theResult">The result of the asynchronous call.</param>
        private static void OnEventCalled< T >( IAsyncResult theResult )
        {
            AsyncResult Result = theResult as AsyncResult;
            if( Result != null )
            {
                try
                {
                    EventHandler< T > InvokedMethod = Result.AsyncDelegate as EventHandler< T >;
                    InvokedMethod?.EndInvoke( Result );
                }
                catch( Exception theException )
                {
                    Action< Exception > ErrorHandler = theResult.AsyncState as Action< Exception >;
                    ErrorHandler?.Invoke( theException );
                }
            }
            else
            {
                throw new InvalidCastException( "The result of the EventCalled is not of the AsyncResult type." );
            }
        }
    }
}