using Logger.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace Logger.Services
{
    public class MonLogger : IMonLogger 
    {
        private Queue<string> _queueAction;
        public MonLogger()
        {
            _queueAction = new Queue<string>();
        }

        public async void Write() 
        {
            if (Monitor.TryEnter(_queueAction))
            {
                try
                {
                    while (_queueAction.Count > 0) 
                    { 
                        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);
                        using StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "Log_aoao.txt"), true);
                        await outputFile.WriteAsync(_queueAction.Dequeue() + Environment.NewLine);
                    }
                }
                finally
                {
                    Monitor.Exit(_queueAction);
                }
            }
        }

        public void AddAction(string action) 
        {
                if (Monitor.TryEnter(_queueAction))
                {
                    try
                    {
                        _queueAction.Enqueue(action);
                    }
                    finally
                    {
                        Monitor.Exit(_queueAction);
                    }
                }
        }
    }
}
