using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SolarPower.Services.Implement
{
    public class SendEmailBackgroundService : IHostedService, IDisposable
    {
        static Timer _timer;
        private int time_interval = 30; //查詢間隔(秒)
        private readonly ILogger<SendEmailBackgroundService> _log;
        private int execCount = 0;

        public SendEmailBackgroundService(ILogger<SendEmailBackgroundService> log)
        {
            this._log = log;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(DoWork, null,
                TimeSpan.Zero,
                TimeSpan.FromSeconds(time_interval));

            return Task.CompletedTask;
        }

        public void DoWork(object state)
        {
            //利用 Interlocked 計數防止重複執行
            if (execCount <= 0)
            {
                Interlocked.Increment(ref execCount);
            }

            if (execCount == 1)
            {
                try
                {
                    
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    Interlocked.Decrement(ref execCount);
                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            //調整Timer為永不觸發，停用定期排程
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
