using System.Security.Cryptography.X509Certificates;
using InABox.Core;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace InABox.IPC
{
    public class RPCServerSocketTransport : RPCServerTransport<RPCServerSocketConnection>
    {
        private WebSocketServer? _server;

        public static X509Certificate2? Certificate { get; set; }
        
        public static void InitCertificate(string certificateFile) => Certificate = new X509Certificate2(certificateFile);
        
        public RPCServerSocketTransport(int port) 
        {
            _server = new WebSocketServer(port,Certificate != null);
            _server.SslConfiguration.ServerCertificate = Certificate;
            _server?.AddWebSocketService( "/", () => new RPCServerSocketConnection() { Transport = this } );
        }
        
        public override void Start()
        {
            _server?.Start();
        }

        public override void Stop()
        {
            _server?.Stop();
        }

        public void ConnectionOpened(RPCServerSocketConnection connection) 
            => DoOpen(connection);

        public void ConnectionException(RPCServerSocketConnection connection, Exception e) 
            => DoException(connection, e);

        public void ConnectionClosed(RPCServerSocketConnection connection, CloseEventArgs e)
            => DoClose(connection, e.Code == 1000 ? RPCTransportCloseEventType.Closed : RPCTransportCloseEventType.Error);
        
    }
}