using System;
using System.Threading.Tasks;
using Grpc.Core;
using Aurora.Backend.Proto;

namespace Aurora.Backend.Services
{
    public class ServerService : BaseService<ServerService>
    {
        private const int Port = 50051;
        private Grpc.Core.Server _server;

        /// <summary>
        /// Constructor. Registers GRPC service implementations.
        /// </summary>
        public ServerService()
        {
            _server = new Grpc.Core.Server
            {
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            Start();
        }

        /// <summary>
        /// Start Server
        /// </summary>
        public void Start()
        {
            _server.Start();
        }

        /// <summary>
        /// Shutdown server async.
        /// </summary>
        /// <returns>Task</returns>
        public async Task Stop()
        {
            await _server.ShutdownAsync();
        }

        public async Task Reset()
        {
            await Stop();
            _server = new Grpc.Core.Server
            {
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
        }

        public void RegisterService(ServerServiceDefinition definition)
        {
            _server.Services.Add(definition);
        }
    }
}