using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ZB.MOM.WW.GRAccess.Cli.Protocol
{
    public static class PipeProtocol
    {
        public const string PipePrefix = "graccess-session-";

        public static string GetPipeName(string galaxyName)
        {
            return PipePrefix + galaxyName.ToLowerInvariant();
        }

        public static async Task WriteMessageAsync<T>(Stream stream, T message)
        {
            var json = JsonConvert.SerializeObject(message, Formatting.None);
            var bytes = Encoding.UTF8.GetBytes(json + "\n");
            await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
            await stream.FlushAsync().ConfigureAwait(false);
        }

        public static async Task<T> ReadMessageAsync<T>(Stream stream)
        {
            using (var reader = new StreamReader(stream, Encoding.UTF8, false, 4096, leaveOpen: true))
            {
                var line = await reader.ReadLineAsync().ConfigureAwait(false);
                if (line == null)
                    return default;
                return JsonConvert.DeserializeObject<T>(line);
            }
        }
    }
}
