// Copyright © 2015 Genesys. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Threading;
using Genesyslab.Desktop.Infrastructure.Commands;
using Genesyslab.Desktop.Infrastructure.DependencyInjection;
using Genesyslab.Desktop.Modules.Gms.CallbackInvitation.Generic;
using Genesyslab.Platform.Commons.Logging;
using Genesyslab.Desktop.Modules.Gms.CallbackInvitation.CallbackInvitation;

namespace Genesyslab.Desktop.Modules.Gms.CallbackInvitation.CustomCommands {
    class BeforeApplicationCloseCommand: IElementOfCommand {
        private readonly IObjectContainer container;
        private readonly ICfgReader config;
        private readonly ILogger log;
        private string _commandName = "BeforeApplicationCloseCommand";

        public BeforeApplicationCloseCommand(IObjectContainer container) {
            this.container = container;
            this.config = this.container.Resolve<ICfgReader>();

            // Initialize the trace system
            this.log = this.container.Resolve<ILogger>().CreateChildLogger(this.Name);
        }

        #region IElementOfCommand Members

        public string Name {
            get { return this._commandName; }
            set { if (this._commandName != value) { this._commandName = value; } }
        }

         public bool Execute(IDictionary<string, object> parameters, IProgressUpdater progress) {
            // To go to the main thread
            if (Application.Current.Dispatcher != null && !Application.Current.Dispatcher.CheckAccess()) {
                object result = Application.Current.Dispatcher.Invoke(DispatcherPriority.Send, new ExecuteDelegate(Execute), parameters, progress);
                return (bool)result;
            }
            else {
                // Ok, we are in the main thread
                this.log.Debug(String.Format("{0} Starting custom {1} functionality", GConst.LOG_PREFIX, this.Name));

                IUserEventListener userEventListener = this.container.Resolve<IUserEventListener>();
                // remove the DN listener
                userEventListener.RemoveHandler();

                this.log.Debug(String.Format("{0} Finished custom {1} functionality", GConst.LOG_PREFIX, this.Name));

                // Always allow remaining elements in the command chain to execute: set return value to false
                return false;
            }
        }

        /// <summary>
        /// This delegate allows to go to the main thread.
        /// </summary>
        delegate bool ExecuteDelegate(IDictionary<string, object> parameters, IProgressUpdater progressUpdater);

        #endregion
    }
}
