using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ServiceStack.Messaging;
using SlnMesnac.Common;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReadService
{
    public class MessageClient
    {
        private readonly RedisHandler _redisHandler;
        private readonly ILogger<MessageClient> _logger;
        private readonly AppConfig _appConfig;

        public MessageClient(RedisHandler redisHandler, ILogger<MessageClient> logger, IConfiguration configuration)
        {
            _redisHandler = redisHandler;
            _logger = logger;
            _appConfig = configuration.GetSection("AppConfig").Get<AppConfig>();
        }

        public void StartListening()
        {
            Console.WriteLine($"启动监听朗读声音服务~~~");

            // 订阅当前工位的频道
            //_redisHandler.SubscribeToChannel($"channel_worker_{_appConfig.stationId}", OnMessageReceivedByWorkId);
            //Console.WriteLine($"订阅工位 ===》channel_worker_{_appConfig.stationId}  成功");
            // 订阅当前工位的频道
            _redisHandler.SubscribeToChannel($"read_messages_public", OnMessageReceived);
            Console.WriteLine($"订阅公共频道==>read_messages_public  成功");
            // 开始处理队列中的未消费消息
            // ProcessMessageQueue();
            // _redisHandler.SubscribeToChannel("read_messages", OnMessageReceived);
        }

        //private async void OnMessageReceivedByWorkId(string channelWork, string messageId)
        //{
        //    try
        //    {
        //        var message =  _redisHandler.ConsumeMessageFromWorker(_appConfig.stationId);
        //        if (!string.IsNullOrEmpty(message))
        //        {
        //            await SpeechStr.Instance.SpeakAsync(message);
        //            Console.WriteLine($"客户端专属频道朗读消息: {message}");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex, "处理消息时发生错误");
        //    }
        //}


        /// <summary>
        /// 公共频道
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="message"></param>
        private async void OnMessageReceived(string channel, string message)
        {
            await SpeechStr.Instance.SpeakAsync(message);
            Console.WriteLine($"客户端公共频道朗读消息{message}");
        }

    }
}
