using InABox.Core;
using WebSocketSharp;
using WebSocketSharp.Server;
using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;

namespace InABox.IPC
{
    public class RPCServerSocketConnection: WebSocketBehavior
    {
        
        public RPCServerSocketTransport? Transport { get; set; }
        
        protected override void OnOpen()
        {
            base.OnOpen();
            Transport?.ConnectionOpened(this);
        }

        protected override void OnClose(CloseEventArgs e)
        {
            base.OnClose(e);
            Transport?.ConnectionClosed(this,e);
        }

        protected override void OnError(ErrorEventArgs e)
        {
            base.OnError(e);
            Transport?.ConnectionException(this, e.Exception);
        }

        protected override void OnMessage(MessageEventArgs e)
        {
            base.OnMessage(e);
            Task.Run(() =>
            {
                RPCMessage? request = null;
                if ((e.IsBinary) && (e.RawData != null))
                    request = Serialization.ReadBinary<RPCMessage>(e.RawData, BinarySerializationSettings.Latest);
                else if ((e.IsText) && !String.IsNullOrWhiteSpace(e.Data))
                    request = Serialization.Deserialize<RPCMessage>(e.Data);

                RPCMessage? response = Transport?.DoMessage(this, request);
                if (response != null)
                {
                    if (e.IsBinary)
                        Send(Serialization.WriteBinary(response, BinarySerializationSettings.Latest));
                    else
                    {
                        Send(Serialization.Serialize(response));
                    }
                }

            });

        }
        
    }
}