using System;
using System.IO;
using System.Text;
using System.Threading;

namespace QC.QMine.QMineInterface;

public class TextLogger : ILogger
{
	public void StartNewLog()
	{
		string path = Path.Combine(Constants.CommandLineModeLogFolderPath, "Log_QMine.txt");
		if (!Directory.Exists(Path.GetDirectoryName(path)))
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
		}
	}

	public void WriteLog(string message, LogType logType)
	{
		if (string.IsNullOrWhiteSpace(message))
		{
			return;
		}
		string path = Path.Combine(Constants.CommandLineModeLogFolderPath, "Log_QMine.txt");
		StringBuilder stringBuilder = new StringBuilder();
		if (stringBuilder.Length > 0)
		{
			stringBuilder.Remove(0, stringBuilder.Length);
		}
		stringBuilder.Append(DateTime.Now.ToString("dd-MMM-yyyy hh mm ss fff tt") + " : ");
		stringBuilder.Append(string.Concat(" Message - ", logType, ":", message));
		Semaphore semaphore = new Semaphore(1, 1);
		try
		{
			StreamWriter streamWriter = null;
			semaphore.WaitOne();
			if (!File.Exists(path))
			{
				StartNewLog();
				streamWriter = File.CreateText(path);
			}
			else
			{
				streamWriter = File.AppendText(path);
			}
			streamWriter.WriteLine(stringBuilder.ToString());
			streamWriter.Close();
			if (logType == LogType.Error && Constants.QMineMode == QMineModes.CommandLine)
			{
				Console.WriteLine("\n" + message);
			}
		}
		catch (Exception)
		{
		}
		finally
		{
			semaphore.Release();
		}
	}
}
