using System;
using System.IO.Pipes;
using System.Threading.Tasks;
using ZB.MOM.WW.GRAccess.Cli.Protocol;

namespace ZB.MOM.WW.GRAccess.Cli.Session
{
    public sealed class SessionClient : IDisposable
    {
        private readonly string _pipeName;

        private SessionClient(string pipeName)
        {
            _pipeName = pipeName;
        }

        /// <summary>
        /// Try to connect to a running session for the given galaxy.
        /// Returns false if no session is available.
        /// </summary>
        public static bool TryConnect(string galaxyName, out SessionClient client)
        {
            client = null;

            var info = SessionInfo.Load(galaxyName);
            if (info == null || !info.IsAlive())
            {
                // Clean up stale file
                info?.Delete();
                return false;
            }

            client = new SessionClient(info.PipeName);
            return true;
        }

        public async Task<PipeResponse> SendCommandAsync(PipeRequest request)
        {
            using (var pipe = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut))
            {
                pipe.Connect(5000);
                await PipeProtocol.WriteMessageAsync(pipe, request).ConfigureAwait(false);
                return await PipeProtocol.ReadMessageAsync<PipeResponse>(pipe).ConfigureAwait(false);
            }
        }

        public Task<PipeResponse> SendShutdownAsync()
        {
            return SendCommandAsync(PipeRequest.Shutdown());
        }

        public Task<PipeResponse> SendStatusAsync()
        {
            return SendCommandAsync(PipeRequest.Status());
        }

        public void Dispose()
        {
            // No persistent resources to clean up — each call opens/closes its own pipe
        }
    }
}
