using System;
using System.IO;
using System.Net;

namespace WS
{
    ///<summary>连接类型</summary>
    public enum ChannelType
	{
		///<summary>连接</summary>
		Connect,
		///<summary>接收</summary>
		Accept,
	}

	///<summary>连接者</summary>
	public abstract class AChannel : WSComponent
	{
		///<summary>连接类型</summary>
		public ChannelType ChannelType { get; }

		///<summary>服务</summary>
		public AService Service { get; }

		///<summary>内存数据操作</summary>
		public abstract MemoryStream Stream { get; }

		///<summary>错误ID</summary>
		public int Error { get; set; }

		///<summary>IP 端口</summary>
		public IPEndPoint RemoteAddress { get; protected set; }


		private Action linkCallback;
		///<summary>链接成功回调</summary>
		public event Action LinkCallback
		{
			add { linkCallback += value; }
			remove { linkCallback -= value; }
		}

		private Action<AChannel, int> errorCallback;
		///<summary>错误回调</summary>
		public event Action<AChannel, int> ErrorCallback
		{
			add { errorCallback += value; }
			remove { errorCallback -= value; }
		}

		private Action<MemoryStream> readCallback;
		///<summary>读取回调</summary>
		public event Action<MemoryStream> ReadCallback
		{
			add { readCallback += value; }
			remove { readCallback -= value; }
		}

		///<summary>读取</summary>
		protected void OnRead(MemoryStream memoryStream)
		{
			readCallback.Invoke(memoryStream);
		}

		///<summary>链接成功回调</summary>
		protected void OnLink()
		{
			linkCallback?.Invoke();
		}

		///<summary>错误回调</summary>
		protected void OnError(int e)
		{
			Error = e;
			errorCallback?.Invoke(this, e);
		}

		protected AChannel(AService service, ChannelType channelType)
		{
			ChannelType = channelType;
			Service = service;
		}

		///<summary>初始</summary>
		public abstract void Start();

		///<summary>发送</summary>
		public abstract void Send(MemoryStream stream);

		public override void Dispose()
		{
			if (IsDisposed)
			{
				return;
			}

			base.Dispose();

			Service.Remove(InstanceId);
		}
	}
}