using System;
using QCRPG.Framework;
using QCRPG.TSL.NFC.Packets;

namespace QCRPG.TSL.NFC;

public class NFCScripterInternal : NFCScripter
{
	private NFCConfigSettings nfcConfigSettings;

	public NFCScripterInternal(NFCAPI nfcAPI, NFCPacketList nfcPacketList, Logger logger, NFCConfigSettings nfcConfigSettings)
		: base(nfcAPI, nfcPacketList, logger)
	{
		this.nfcConfigSettings = nfcConfigSettings;
		tclCommandMap.Add("WriteNFCNVMFile", WriteNFCNVMFile_Handler);
		tclCommandMap.Add("WriteNfcNVMFile", WriteNFCNVMFile_Handler);
	}

	private TclResult WriteNFCNVMFile_Handler(string[] args)
	{
		if (args.Length < 2 || args.Length > 3)
		{
			TclWrapper.SetResult(string.Format("Wrong # of arguments.  Usage: {0} ?forceWrite? ?filenameOverride? or {0} ?forceWrite?", args[0]));
			return TclResult.ERROR;
		}
		string filename = "";
		if (args[1] == "1")
		{
			logger.Enqueue(new LogMessage(LogMessageType.Info, "Forcing NFC NVM download regardless of application setting"));
		}
		else
		{
			if (!nfcConfigSettings.LoadNFCNVMFile)
			{
				logger.Enqueue(new LogMessage(LogMessageType.Info, "Not doing NFC NVM download because of application setting"));
				return TclResult.OK;
			}
			logger.Enqueue(new LogMessage(LogMessageType.Info, "Doing NFC NVM download because of application setting"));
		}
		if (args.Length == 2)
		{
			filename = nfcConfigSettings.DefaultNFCNVMFile;
			logger.Enqueue(new LogMessage(LogMessageType.Info, "Using filename specified by application"));
		}
		else if (args.Length == 3)
		{
			filename = args[2];
			logger.Enqueue(new LogMessage(LogMessageType.Info, "Using filename passed by script"));
		}
		try
		{
			nfcAPI.WriteNVM(filename);
		}
		catch (Exception ex)
		{
			TclWrapper.SetResult($"Caught exception writing NVM file.\r\nSource: {ex.Source}\r\nMessage: {ex.Message}");
			return TclResult.ERROR;
		}
		return TclResult.OK;
	}
}
