using System.Collections.Concurrent;

namespace Inspectron.Statistics;

public class StatisticsWritter:IStatistics
{
    private readonly Func<IStatistics> _statisticsBuilder;

    private bool _running = true;
    public StatisticsWritter(Func<IStatistics> statisticsBuilder)
    {
        _statisticsBuilder = statisticsBuilder;
        Thread th = new Thread(WritingLoop);
        th.IsBackground = false;
        th.Start();
    }

    private void WritingLoop()
    {
        while (_running)
        {
            try
            {
                using (var statistics = _statisticsBuilder())
                {
                    while (_recordQueue.TryDequeue(out var res))
                    {
                        var error = false;
                        do
                        {
                            try
                            {
                                statistics.WriteLine(res);
                            }
                            catch (Exception e)
                            {
                                error = true;
                                Thread.Sleep(1000);
                            }
                        } while (error);

                    }
                }
            }
            catch
            {

            }

            Thread.Sleep(1000);
        }
    }

    public void Dispose()
    {
        _running = false;
    }

    private ConcurrentQueue<StatisticsRecord> _recordQueue = new ConcurrentQueue<StatisticsRecord>();
    public void WriteLine(StatisticsRecord record)
    {
        _recordQueue.Enqueue(record);
    }
}