using System;
using Decal.Adapter.NetParser;
using Decal.Adapter.Support;
using Decal.Interop.Filters;
using Decal.Interop.Net;

namespace Decal.Adapter.Wrappers;

public class EchoFilter2 : GenericDisposableWrapper<Decal.Interop.Filters.EchoFilter2>
{
	private event EventHandler<NetworkMessageEventArgs> serverDispatch;

	private event EventHandler<NetworkMessageEventArgs> clientDispatch;

	/// <summary>
	/// Fires when the client receives a message from the server
	/// </summary>
	public event EventHandler<NetworkMessageEventArgs> ServerDispatch
	{
		add
		{
			serverDispatch += value;
		}
		remove
		{
			serverDispatch -= value;
		}
	}

	/// <summary>
	/// Fires when the client sends a message to the server
	/// </summary>
	public event EventHandler<NetworkMessageEventArgs> ClientDispatch
	{
		add
		{
			clientDispatch += value;
		}
		remove
		{
			clientDispatch -= value;
		}
	}

	public EchoFilter2(Decal.Interop.Filters.EchoFilter2 obj)
		: base(obj)
	{
		base.Wrapped.EchoClient += onEchoClient;
		base.Wrapped.EchoServer += onEchoServer;
	}

	protected override void Dispose(bool userCalled)
	{
		if (userCalled && base.Wrapped != null)
		{
			base.Wrapped.EchoClient -= onEchoClient;
			base.Wrapped.EchoServer -= onEchoServer;
		}
		base.Dispose(userCalled);
	}

	private void onEchoServer(IMessage2 pMsg)
	{
		try
		{
			Message message = null;
			Util.SafeFireEvent(args: new NetworkMessageEventArgs((!(pMsg is MessageWrapper messageWrapper)) ? new Message(pMsg, MessageDirection.Inbound) : messageWrapper.Wrapped), sender: this, eventHandler: this.serverDispatch);
		}
		catch (Exception ex)
		{
			Util.WriteLine("Exception in onEchoServer {0}", ex);
		}
	}

	private void onEchoClient(IMessage2 pMsg)
	{
		try
		{
			Message message = null;
			Util.SafeFireEvent(args: new NetworkMessageEventArgs((!(pMsg is MessageWrapper messageWrapper)) ? new Message(pMsg, MessageDirection.Inbound) : messageWrapper.Wrapped), sender: this, eventHandler: this.clientDispatch);
		}
		catch (Exception ex)
		{
			Util.WriteLine("Exception in onEchoClient {0}", ex);
		}
	}
}
