namespace HuanMeng.DotNetCore.Processors
{
    /// <summary>
    /// 包含处理线程的处理器基类
    /// </summary>
    public abstract class ThreadProcessor : BaseProcessor
    {
        protected Thread? _thread;
        protected bool _isRunning;
        protected string? _threadName;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ThreadProcessor() { }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="threadName">线程名称</param>
        public ThreadProcessor(string threadName)
        {
            _threadName = threadName;
        }

        /// <summary>
        /// 执行处理
        /// </summary>
        /// <exception cref="InvalidOperationException">如果处理器已经在运行，抛出异常</exception>
        public override void Run()
        {
            if (_isRunning)
            {
                throw new InvalidOperationException("重复执行线程");
            }

            _isRunning = true;

            _thread = new Thread(Proc_Do)
            {
                Name = _threadName
            };
            _thread.Start();
        }

        /// <summary>
        /// 线程处理函数，需要在子类中实现
        /// </summary>
        protected abstract void Proc_Do();

        /// <summary>
        /// 停止处理线程
        /// </summary>
        public override void Stop()
        {
            if (!_isRunning)
            {
                return;
            }

            _isRunning = false;

            if (_thread != null && _thread.IsAlive)
            {
                _thread.Join(WaitTimeMax_StopProc); // 等待线程结束
                _thread = null;
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public override void Dispose()
        {
            Stop();
            base.Dispose();
        }


    }
}
