using System;
using QCRPG.Framework;

namespace QCRPG.TSL.FM.Packets;

public class TuneInfo : PacketInfoBase
{
	private static uint tuneOffset = 87500u;

	public override string Name => "Tune";

	public override string DisplayGroup => "Control";

	public static uint TuneOffset
	{
		get
		{
			return tuneOffset;
		}
		set
		{
			tuneOffset = value;
		}
	}

	public TuneInfo(Tune packet)
		: base(packet)
	{
		UpdateFieldInfoFromPacket();
	}

	public override void UpdateFieldInfoFromPacket()
	{
		Tune tune = (Tune)packet;
		fieldInfoList.Clear();
		fieldInfoList.Add(new PacketFieldInfo("Register Address", RegisterMapInfo.RegisterMapToDescription(), 8, FormatValue(tune.UserFields.RegisterAddress, 8), RegisterMapInfo.RegisterMapToString(RegisterMapInfo.ValueToRegisterMap(tune.UserFields.RegisterAddress)), "", "", settable: false, littleEndianTransport: false, omitFromTransport: false, DataEntryMode.RightAlignedHex));
		fieldInfoList.Add(new PacketFieldInfo("Tune Frequency", "Tune frequency in 100kHz units from current band's lowest frequency; enter this value as an integer frequency in kHz", 8, FormatValue(tune.UserFields.TuneFrequency, 8), "", "", "", settable: true, littleEndianTransport: false, omitFromTransport: false, DataEntryMode.Custom));
		fieldInfoList.Add(new PacketFieldInfo("Tune Control", "", 8, FormatValue(tune.UserFields.TuneControl, 8), "", "", "", settable: false, littleEndianTransport: false, omitFromTransport: false, DataEntryMode.RightAlignedHex));
	}

	public override void UpdatePacketFromFieldInfo(int index, string value)
	{
		Tune tune = (Tune)packet;
		int num = -1;
		if (index == ++num)
		{
			throw new Exception("Tried to set non-settable field RegisterAddress");
		}
		if (index == ++num)
		{
			tune.UserFields.TuneFrequency = Convert.ToUInt32(value, 16);
		}
		else if (index == ++num)
		{
			throw new Exception("Tried to set non-settable field TuneControl");
		}
	}

	public override string ConvertFieldDisplayedTextToHexString(string fieldName, string displayedText)
	{
		if (fieldName == "Tune Frequency")
		{
			uint num = Convert.ToUInt32(displayedText);
			if (num < tuneOffset)
			{
				throw new Exception("Frequency cannot be smaller than the tune offset of " + tuneOffset);
			}
			return ((num - tuneOffset) / 100).ToString("X");
		}
		return base.ConvertFieldDisplayedTextToHexString(fieldName, displayedText);
	}

	public override string ConvertFieldHexStringToDisplayedText(string fieldName, string hexString)
	{
		if (fieldName == "Tune Frequency")
		{
			return (Convert.ToUInt32(hexString, 16) * 100 + tuneOffset).ToString();
		}
		return base.ConvertFieldHexStringToDisplayedText(fieldName, hexString);
	}
}
