using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Text;

namespace ASHermed.SinoInterface.Tools.Base
{
    public abstract class BaseConsumer : IConsumer
    {
        protected IConnection Connection;
        protected IModel Channel;
        protected EventingBasicConsumer Consumer;

        public void UnSubscribe()
        {
            if (Consumer != null)
            {
                Consumer = null;
            }
            if (Channel != null && Channel.IsOpen)
            {
                Channel.Close();
                Channel.Dispose();
            }
            if (Connection != null && Connection.IsOpen)
            {
                Connection.Close();
                Connection.Dispose();
            }
        }

        public bool IsRunning()
        {
            return Consumer != null && Consumer.IsRunning;
        }

        public abstract void Subscribe();

        protected const int MAX_RETRY_COUNT = 20;

        public void ProcessingResults(IModel channel, BasicDeliverEventArgs eventArgs, Tuple<bool, string> tuple, RedisHelperClient redisHelperClient, string redisKey)
        {
            if (tuple.Item1)
            {
                channel.BasicAck(eventArgs.DeliveryTag, false);
                redisHelperClient.Set(redisKey, "1");
            }
            else
            {
                RejectInvoke(channel, eventArgs);
            }
        }
        public void RejectInvoke(IModel channel, BasicDeliverEventArgs eventArgs)
        {
            var list = new List<object>();
            if (eventArgs.BasicProperties.Headers != null && eventArgs.BasicProperties.Headers.Keys.Contains("x-death"))
            {
                list = (List<object>)eventArgs.BasicProperties.Headers["x-death"];
            }
            if (list.Count < MAX_RETRY_COUNT)
            {
                channel.BasicReject(eventArgs.DeliveryTag, false);
            }
            else
            {
                channel.BasicAck(eventArgs.DeliveryTag, false);
            }
        }
    }
}
