using System;
using System.IO;
using System.Text;
using System.Threading;
using QC.CTDS.DM.DataStructures;
using QC.CTDS.DM.SharedLibrary;

namespace QC.CTDS.DM.ServicePlugins.CommandLineService;

public class TextLogger : ILogger
{
	public string CurrentLogFileName { get; set; }

	public TextLogger()
	{
		CurrentLogFileName = Constants.DefaultTempFilePath + "\\Logs\\Log_QMine_" + DateTime.Now.ToString("dd-MMM-yyyy_hh_mm_ss_fff_tt") + ".txt";
		if (!Directory.Exists(Path.GetDirectoryName(CurrentLogFileName)))
		{
			Directory.CreateDirectory(Path.GetDirectoryName(CurrentLogFileName));
		}
	}

	public void WriteLog(string message, LogType logType)
	{
		StringBuilder stringBuilder = new StringBuilder();
		if (string.IsNullOrWhiteSpace(message))
		{
			return;
		}
		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(CurrentLogFileName))
			{
				if (!Directory.Exists(Path.GetDirectoryName(CurrentLogFileName)))
				{
					Directory.CreateDirectory(Path.GetDirectoryName(CurrentLogFileName));
				}
				streamWriter = File.CreateText(CurrentLogFileName);
			}
			else
			{
				streamWriter = File.AppendText(CurrentLogFileName);
			}
			streamWriter.WriteLine(stringBuilder.ToString());
			streamWriter.Close();
		}
		catch (Exception)
		{
		}
		finally
		{
			semaphore.Release();
		}
	}
}
