using System;
using System.Runtime.InteropServices;

namespace QC.QMSLPhone;

public class LogMessage : AsyncMessage
{
	[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 16)]
	public struct LogMeasurementHdrType
	{
		public byte cmdCode;

		public byte more;

		public ushort length;

		public ushort length2;

		public ushort logCode;

		public ulong timeStamp;
	}

	protected const int logHdrSize = 16;

	private const int HeaderLen = 16;

	private GCHandle pinnedPacket;

	private IntPtr p;

	public LogMeasurementHdrType logHdr;

	private bool displayRaw;

	public LogMessage(ushort logCodeVal, byte[] messageVal)
		: base(logCodeVal, messageVal)
	{
		displayRaw = true;
		overlayStructure(logCodeVal, messageVal);
	}

	public LogMessage(ushort logCodeVal, byte[] messageVal, bool displayRawVal)
		: base(logCodeVal, messageVal)
	{
		displayRaw = displayRawVal;
		overlayStructure(logCodeVal, messageVal);
	}

	private void overlayStructure(ushort logCodeVal, byte[] messageVal)
	{
		pinnedPacket = GCHandle.Alloc(messageVal, GCHandleType.Pinned);
		p = pinnedPacket.AddrOfPinnedObject();
		logHdr = (LogMeasurementHdrType)Marshal.PtrToStructure(p, typeof(LogMeasurementHdrType));
	}

	public byte getPayloadByte(int stIndex)
	{
		return message[stIndex + 16];
	}

	public short getPayloadShort(int stIndex)
	{
		return getShort(stIndex + 16);
	}

	public ushort getPayloadWord(int stIndex)
	{
		return getWord(stIndex + 16);
	}

	public uint getPayloadUint32(int stIndex)
	{
		return getUint32(stIndex + 16);
	}

	public ulong getPayloadUint64(int stIndex)
	{
		return getUint64(stIndex + 16);
	}

	public string getTimeStamp()
	{
		double num = logHdr.timeStamp >> 16;
		num *= 1.0 / 800.0;
		int num2 = (int)(num / 86400.0);
		num -= (double)num2 * 86400.0;
		int num3 = (int)(num / 3600.0);
		num -= (double)num3 * 3600.0;
		int num4 = (int)(num / 60.0);
		num -= (double)num4 * 60.0;
		return $"{num3:00}:{num4:00}:{num:00.000}";
	}

	public override string ToString()
	{
		string text = $"0x{logHdr.logCode:X} {getTimeStamp()} ";
		if (displayRaw)
		{
			return text + base.ToString();
		}
		return text;
	}
}
