using System;
using System.Runtime.InteropServices;
using System.Text;

namespace QC.QMSLPhone;

internal class MassStorageDownload
{
	public delegate void SwDownloadEventHandler(object sender, string information);

	public enum ValidationMethodOption
	{
		ValidateDuringDownload,
		ValidateAfterDownload
	}

	private const string emmcDownloadDllName = "eMMCDownload.dll";

	private SWDownloadEMMCLogHandlerCallBack swdownloadEMMCloghandlerCallBack_delegate;

	private string skipFiles = "";

	private int validationMethod = 1;

	public event SwDownloadEventHandler OnSwDownloadEvent;

	public MassStorageDownload()
	{
		swdownloadEMMCloghandlerCallBack_delegate = swdownloademmcLogHandlerCallBack;
	}

	[DllImport("eMMCDownload.dll", SetLastError = true)]
	private static extern byte QEMMCLib_UploadEmmcImage(string rawProgramFileName, string patchFileName, string imageDirectory, string driveName, bool enableValidation, ref uint iErrorCode, SWDownloadEMMCLogHandlerCallBack pSWDLEMMCCallback, string skipFiles = "");

	[DllImport("eMMCDownload.dll", SetLastError = true)]
	private static extern byte QEMMCLib_UploadEmmcImageWithValidation(string rawProgramFileName, string patchFileName, string imageDirectory, string driveName, ref uint iErrorCode, SWDownloadEMMCLogHandlerCallBack pSWDLEMMCCallback, string skipFiles = "");

	private bool swdownloademmcLogHandlerCallBack(IntPtr msgPtr, int MsgSize)
	{
		try
		{
			byte[] array = new byte[MsgSize];
			Marshal.Copy(msgPtr, array, 0, MsgSize);
			UTF8Encoding uTF8Encoding = new UTF8Encoding();
			string @string = uTF8Encoding.GetString(array);
			UpdateSwDownloadClient(@string);
			return true;
		}
		catch (Exception ex)
		{
			throw ex;
		}
	}

	public void UpdateSwDownloadClient(string information)
	{
		if (this.OnSwDownloadEvent != null)
		{
			this.OnSwDownloadEvent(this, information);
		}
	}

	public void MassStorageSetParameters(int iValidationMethod, string filenames)
	{
		validationMethod = iValidationMethod;
		skipFiles = filenames;
	}

	public void UploadEmmcImage(string rawProgramFileName, string patchFileName, string imageDirectory, string driveName, bool enableValidation, ref uint iErrorCode, SWDownloadEMMCLogHandlerCallBack pSWDLEMMCCallback)
	{
		byte b = 0;
		b = ((!enableValidation || validationMethod != 1) ? QEMMCLib_UploadEmmcImage(rawProgramFileName, patchFileName, imageDirectory, driveName, enableValidation, ref iErrorCode, pSWDLEMMCCallback, skipFiles) : QEMMCLib_UploadEmmcImageWithValidation(rawProgramFileName, patchFileName, imageDirectory, driveName, ref iErrorCode, pSWDLEMMCCallback, skipFiles));
		if (b != 1)
		{
			throw new Exception("Failed to program the eMMC image to the phone:  " + iErrorCode);
		}
	}
}
