using System;
using System.Text;
using QCRPG.Framework;

namespace QCRPG.TSL.NFC;

public class NFCFirmwarePatchTypeHandler
{
	public enum PatchType
	{
		Binary,
		String,
		Unknown
	}

	private PatchType patchType = PatchType.Unknown;

	private byte[] data;

	private byte[] dataAsBinary;

	private string dataAsString;

	public NFCFirmwarePatchTypeHandler(byte[] data)
	{
		this.data = data;
		DetectTypeAndConvertData();
	}

	public PatchType GetPatchType()
	{
		return patchType;
	}

	public string GetPatchDataAsString()
	{
		if (patchType == PatchType.Binary || patchType == PatchType.String)
		{
			return dataAsString;
		}
		throw new Exception("Can't return data for patch type " + patchType);
	}

	public byte[] GetPatchDataAsBinary()
	{
		if (patchType == PatchType.Binary || patchType == PatchType.String)
		{
			return dataAsBinary;
		}
		throw new Exception("Can't return data for patch type " + patchType);
	}

	private void DetectTypeAndConvertData()
	{
		patchType = PatchType.Unknown;
		if (data == null)
		{
			dataAsBinary = null;
			dataAsString = "";
			return;
		}
		string text = Conversions.ByteArrayToString(data).Trim();
		if (text.Contains(" "))
		{
			string[] array = text.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			text = "";
			string[] array2 = array;
			foreach (string value in array2)
			{
				try
				{
					text += Convert.ToByte(value, 16).ToString("X2");
				}
				catch (Exception)
				{
					patchType = PatchType.Binary;
					break;
				}
			}
		}
		byte[] array3 = null;
		if (patchType == PatchType.Unknown)
		{
			try
			{
				array3 = Conversions.HexStringToByteArray(text);
				patchType = PatchType.String;
			}
			catch (Exception)
			{
				patchType = PatchType.Binary;
			}
		}
		if (patchType == PatchType.Binary)
		{
			dataAsBinary = data;
			dataAsString = Conversions.ByteArrayToSpacedHexString(data);
		}
		else if (patchType == PatchType.String)
		{
			dataAsBinary = array3;
			StringBuilder stringBuilder = new StringBuilder();
			for (int j = 0; j < text.Length; j += 2)
			{
				stringBuilder.Append(text.Substring(j, 2));
				stringBuilder.Append(" ");
			}
			dataAsString = stringBuilder.ToString().TrimEnd();
		}
	}
}
