using System;
using System.ServiceModel;
using System.Threading;
using System.Windows;
using Aitex.Core.RT.Log;
using Aitex.Core.Utilities;

namespace Aitex.Core.WCF
{
	public abstract class ServiceClientWrapper<T>
	{
		#region Variables

		private readonly ChannelFactory<T> _factory;
		private readonly string _serviceName;
		private T _proxy;
		private bool _isInError;
		private bool _isAbortByUser;
		private Retry _retryConnect = new();
		
		#endregion

		#region Constructors

		protected ServiceClientWrapper(string endpointConfigurationName, string name)
		{
			_serviceName = name;
			try
			{
				_factory = new ChannelFactory<T>(endpointConfigurationName);
			}
			catch (Exception ex)
			{
				MessageBox.Show("不能创建Service " + name + "，检查配置：" + endpointConfigurationName);
				LOG.Error("不能创建Service " + name + "，检查配置：" + endpointConfigurationName, ex);
			}
		}

		protected ServiceClientWrapper(string endpointConfigurationName, string name, EndpointAddress address)
		{
			_serviceName = name;
			try
			{
				_factory = new ChannelFactory<T>(endpointConfigurationName, address);
			}
			catch (Exception ex)
			{
				MessageBox.Show("不能创建Service " + name + "，检查配置：" + endpointConfigurationName);
				LOG.Error("不能创建Service " + name + "，检查配置：" + endpointConfigurationName, ex);
			}
		}

		#endregion

		#region Properties

		public bool ActionFailed => _isInError;

		#endregion


		#region Methods

		/// <summary>
		/// 执行指定的方法。
		/// </summary>
		/// <param name="action"></param>
		protected void Invoke(Action<T> action)
		{
			if (_factory == null)
				return;
            
			_proxy ??= _factory.CreateChannel();
			
			for (var i = 0; i < 2; i++)
			{
				if (Do(action))
					break;
				
				Thread.Sleep(10);
			}
		}

		private bool Do(Action<T> action)
		{
			if (_proxy != null && ((IClientChannel)_proxy).State == CommunicationState.Faulted)
			{
				((IClientChannel)_proxy).Abort();
				_proxy = _factory.CreateChannel();
			}
			try
			{
				action(_proxy);
				if (_isInError)
				{
					_isInError = false;
					LOG.Info(_serviceName + " 服务恢复", isTraceOn: false);
				}
				return true;
			}
			catch (EndpointNotFoundException ex)
			{
				if (!_isInError)
				{
					_isInError = true;
					LOG.Error(_serviceName + " 连接已经断开.", ex);
				}
			}
			catch (ProtocolException ex2)
			{
				if (!_isInError)
				{
					_isInError = true;
					LOG.Error(_serviceName + " 服务程序异常.", ex2);
				}
			}
			catch (Exception ex3)
			{
                if (_isAbortByUser)
                {
                    _isAbortByUser = false;
                    return true;
                }

				if (!_isInError)
				{
					_isInError = true;
					LOG.Error(_serviceName + " 服务异常", ex3);
				}
			}
			((IClientChannel)_proxy)?.Abort();
			_proxy = _factory.CreateChannel();
			return false;
		}

		#endregion
	}
}
