using System.IO;
using XP.Hardware.RaySource.Comet.Messages;
using XP.Hardware.RaySource.Comet.Messages.Responses;

namespace XP.Hardware.RaySource.Comet.Host.Pipe
{
    /// <summary>
    /// 推送管理器
    /// 负责将主动推送消息通过管道发送给主进程
    /// </summary>
    static class PushNotifier
    {
        private static StreamWriter _writer;
        private static object _writeLock;

        /// <summary>
        /// 初始化推送管理器
        /// </summary>
        /// <param name="writer">管道写入器</param>
        /// <param name="writeLock">写入锁对象</param>
        public static void Initialize(StreamWriter writer, object writeLock)
        {
            _writer = writer;
            _writeLock = writeLock;
        }

        /// <summary>
        /// 发送推送消息给主进程
        /// 使用 lock 保护写入，防止与命令响应交错
        /// </summary>
        /// <param name="response">推送响应对象（IsPush 应为 true）</param>
        public static void SendPush(RaySourceResponse response)
        {
            if (_writer == null || _writeLock == null)
                return;

            response.IsPush = true;
            var json = MessageSerializer.Serialize(response);
            lock (_writeLock)
            {
                _writer.WriteLine(json);
            }
        }
    }
}
