using System;
using System.Threading;
using QCRPG.Framework;

namespace QCRPG.TSL.FMHCI;

public class FMHCIMainWorkerThread : WorkerThreadBase
{
	private ManualResetEvent writeNvmEvent = new ManualResetEvent(initialState: false);

	private ManualResetEvent patchFirmwareEvent = new ManualResetEvent(initialState: false);

	private ManualResetEvent loadSpurTableEvent = new ManualResetEvent(initialState: false);

	private FMHCIAPI fmhciAPI;

	private string nvmFilename;

	private string patchFilename;

	private string spurTableFilename;

	public FMHCIMainWorkerThread(Logger logger, FMHCIAPI fmhciAPI)
		: base(logger)
	{
		this.fmhciAPI = fmhciAPI;
	}

	public void WriteNvm(string filename)
	{
		nvmFilename = filename;
		writeNvmEvent.Set();
	}

	public void PatchFirmware(string filename)
	{
		patchFilename = filename;
		patchFirmwareEvent.Set();
	}

	public void LoadSpurTable(string filename)
	{
		spurTableFilename = filename;
		loadSpurTableEvent.Set();
	}

	protected override void Run()
	{
		logger.Enqueue(new LogMessage(LogMessageType.Info, "FM HCI main thread starting"));
		ManualResetEvent[] array = new ManualResetEvent[4] { writeNvmEvent, patchFirmwareEvent, loadSpurTableEvent, shutdownThreadEvent };
		while (true)
		{
			int num = WaitHandle.WaitAny(array);
			if (array[num] == writeNvmEvent)
			{
				WriteNvmHandler(nvmFilename);
				writeNvmEvent.Reset();
			}
			else if (array[num] == patchFirmwareEvent)
			{
				PatchFirmwareHandler(patchFilename);
				patchFirmwareEvent.Reset();
			}
			else if (array[num] == loadSpurTableEvent)
			{
				LoadSpurTableHandler(spurTableFilename);
				loadSpurTableEvent.Reset();
			}
			else if (array[num] == shutdownThreadEvent)
			{
				break;
			}
		}
		logger.Enqueue(new LogMessage(LogMessageType.Info, "FM HCI main thread ending"));
	}

	private void WriteNvmHandler(string filename)
	{
		try
		{
			fmhciAPI.WriteNVM(filename);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new LogMessage(LogMessageType.Error, ex));
			MessageBoxes.ShowErrorBox("Error writing FM HCI NVM");
		}
	}

	private void PatchFirmwareHandler(string filename)
	{
		try
		{
			fmhciAPI.PatchFirmware(filename);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new LogMessage(LogMessageType.Error, ex));
			MessageBoxes.ShowErrorBox("Error patching FM HCI firmware");
		}
	}

	private void LoadSpurTableHandler(string filename)
	{
		try
		{
			fmhciAPI.LoadSpurTable(filename);
		}
		catch (Exception ex)
		{
			logger.Enqueue(new LogMessage(LogMessageType.Error, ex));
			MessageBoxes.ShowErrorBox("Error loading FM HCI spur table");
		}
	}
}
