using System;
using System.IO;
using System.Threading;
using QC.QTMDotNetKernelInterface;
using QC.QTMDotNetKernelInterface.Environment;

namespace QC.QTMToolKit.Tools;

[QTMTestClass]
public class QTMTools : QSPRTest
{
	private string globalVariableName = "";

	private string globalVariableValue = "";

	private string globalVariableGetValue = "";

	private int duration;

	private int stopAbortCheckInterval;

	private string configFilePath;

	[QTMParameter(ParameterIOType.Input, TestList = "SetGlobalVariable,GetGlobalVariable", Description = "Name of the Global Variable.")]
	public string Name
	{
		get
		{
			return globalVariableName;
		}
		set
		{
			globalVariableName = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "SetGlobalVariable", Description = "Value of the Global Variable.")]
	public string Value
	{
		get
		{
			return globalVariableValue;
		}
		set
		{
			globalVariableValue = value;
		}
	}

	[QTMParameter(ParameterIOType.Output, TestList = "GetGlobalVariable", Description = "Value of the Global Variable.")]
	public string CurrentValue
	{
		get
		{
			return globalVariableGetValue;
		}
		set
		{
			globalVariableGetValue = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, UnitOfMeasure = "msec", DefaultValue = "0", TestList = "Sleep", Description = "The number of milliSeconds for which thead is blocked.")]
	public int Duration
	{
		get
		{
			return duration;
		}
		set
		{
			duration = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, UnitOfMeasure = "msec", DefaultValue = "1000", TestList = "Sleep", Description = "Interval in milliSeconds for checking STOP or ABORT message.")]
	public int StopAbortCheckInterval
	{
		get
		{
			return stopAbortCheckInterval;
		}
		set
		{
			stopAbortCheckInterval = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, DefaultValue = "c:\\QSPR\\Configs", TestList = "SetConfigFilePath", Description = " Overrides the Config file path set in the Root Folder", UnitOfMeasure = " ", Constraints = " ", DisplayHint = DisplayHints.FILE, NumberOfElements = 1)]
	public string ConfigFilePath
	{
		get
		{
			return configFilePath;
		}
		set
		{
			configFilePath = value;
		}
	}

	public QTMTools(QSPREnvironment qsprEnv)
		: base(qsprEnv)
	{
	}

	[QTMTest(Description = "Set a global variable", CanAddToTestPlan = true)]
	public bool SetGlobalVariable()
	{
		return base.Env.GlobalVariable.SetGlobalVariable(globalVariableName, globalVariableValue);
	}

	[QTMTest(Description = "Registers the technology which will be included in TECHNOLOGIES global variable and used for QDART logging configuration", CanAddToTestPlan = true)]
	public bool RegisterTechnology(char Tech)
	{
		return base.Env.GlobalVariable.RegisterTechnology(Tech);
	}

	[QTMTest(Description = "Sets the current dut index which will be saved to the DUT_INDEX global variable and used for QDART logging configuration", CanAddToTestPlan = true)]
	public bool SetDutIndex(uint DutIndex)
	{
		return base.Env.GlobalVariable.SetDutIndex(DutIndex);
	}

	[QTMTest(Description = "Get a global variable", CanAddToTestPlan = true)]
	public bool GetGlobalVariable()
	{
		return base.Env.GlobalVariable.GetGlobalVariable(globalVariableName, out globalVariableGetValue);
	}

	[QTMTest(Description = "Sleeps for the length od Duration parameter. Checks for Stop/Abort message at every stopAbortCheckInterval parameter value", CanAddToTestPlan = true)]
	public bool Sleep()
	{
		int num = Duration / StopAbortCheckInterval;
		int millisecondsTimeout = Duration % StopAbortCheckInterval;
		for (int i = 0; i < num; i++)
		{
			Thread.Sleep(StopAbortCheckInterval);
			if (base.Env.QTMInfo.CheckForAnyStopAbortMsg)
			{
				break;
			}
		}
		if (!base.Env.QTMInfo.CheckForAnyStopAbortMsg)
		{
			Thread.Sleep(millisecondsTimeout);
		}
		return true;
	}

	[QTMTest("Sets an output parameter 'Error Code' with value from the input Parameter 'erroCode'", CanAddToTestPlan = true)]
	public bool SetErrorCode(string ErrorCodeValue, string Description, out string ErrorCode, out string ErrorDescription)
	{
		ErrorCode = ErrorCodeValue;
		ErrorDescription = Description;
		return true;
	}

	[QTMTest(CanAddToTestPlan = true)]
	public bool SetConfigFilePath()
	{
		return base.Env.GlobalVariable.SetGlobalVariable("ConfigFilePath", ConfigFilePath);
	}

	[QTMTest(Description = "Gets a folder path given a filename. If the filename given doesn't exist, or an exception is thrown, the test returns failure and folderPath is left empty.")]
	[QTMParameter(ArgumentName = "FileName", Description = "The name of the filename whose path should be returned.")]
	[QTMParameter(ArgumentName = "FolderPath", Description = "The folder path returned.")]
	[QTMParameter(ArgumentName = "IncludeTrailingBackslash", DefaultValue = "True", Description = "If true, folderPath will include a trailing path separator.")]
	public bool GetFolderPath(string FileName, out string FolderPath, bool IncludeTrailingBackslash)
	{
		FolderPath = "";
		try
		{
			FileInfo fileInfo = new FileInfo(FileName);
			if (!fileInfo.Exists)
			{
				return false;
			}
			FolderPath = fileInfo.DirectoryName;
			if (IncludeTrailingBackslash)
			{
				FolderPath += Path.DirectorySeparatorChar;
			}
		}
		catch
		{
			return false;
		}
		return true;
	}

	[QTMParameter(ArgumentName = "debugWindowNames", Description = " Debug Window Names separated by comma.  Leave blank to save all debug messages.")]
	[QTMTest(Description = "Saves debug messages for specified Debug window names or save all debug messages if debugWindowNames is blank.", CanAddToTestPlan = true)]
	[QTMParameter(ArgumentName = "appendText", DefaultValue = "True", Description = "Append text to an existing file, if the file does not existed, it is created. ")]
	[QTMParameter(ArgumentName = "clearAfterSave", Description = "Clears the Debug messages from the window after saving")]
	public bool SaveDebugMessages(string debugWindowNames, bool appendText, bool clearAfterSave)
	{
		try
		{
			if (string.IsNullOrEmpty(debugWindowNames))
			{
				base.Env.DebugMessage.SaveAll(appendText);
				if (clearAfterSave)
				{
					base.Env.DebugMessage.ClearAll();
				}
			}
			else
			{
				string[] array = debugWindowNames.Split(',');
				string[] array2 = array;
				foreach (string debugWindowName in array2)
				{
					base.Env.DebugMessage.Save(debugWindowName, appendText);
					if (clearAfterSave)
					{
						base.Env.DebugMessage.Clear(debugWindowName);
					}
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			base.Env.DebugMessage.Write("SaveDebugMessages", $" Save Debug messages failed for {debugWindowNames} {ex.Message}.");
			return false;
		}
	}

	[QTMParameter(ArgumentName = "debugWindowNames", Description = " Debug Window Names separated by comma.  Leave blank to clear all debug messages.")]
	[QTMTest(Description = "Clear debug messages for specified Debug window names or clear all debug messages if debug Window Names are blank.", CanAddToTestPlan = true)]
	public bool ClearDebugMessages(string debugWindowNames)
	{
		try
		{
			if (string.IsNullOrEmpty(debugWindowNames))
			{
				base.Env.DebugMessage.ClearAll();
			}
			else
			{
				string[] array = debugWindowNames.Split(',');
				string[] array2 = array;
				foreach (string debugWindowName in array2)
				{
					base.Env.DebugMessage.Clear(debugWindowName);
				}
			}
			return true;
		}
		catch (Exception ex)
		{
			base.Env.DebugMessage.Write("ClearDebugMessages", $" Clear Debug messages failed for {debugWindowNames} {ex.Message}.");
			return false;
		}
	}

	[QTMParameter(ArgumentName = "DebugWindowName", Description = "The name of the debug window to show.")]
	[QTMTest(Description = "Sets the debug window tab in focus if it exists. NOTE: This has no effect if the debug windows are not organized in tabs.")]
	public bool SetDebugWindowInFocus(string DebugWindowName)
	{
		base.Env.DebugMessage.SetDebugWindowInFocus(DebugWindowName);
		return true;
	}

	[QTMTest(Description = "Starts Logging", CanAddToTestPlan = true)]
	public bool StartLogging()
	{
		try
		{
			base.Env.DebugMessage.StartLogging();
			return true;
		}
		catch
		{
			return false;
		}
	}

	[QTMTest(Description = "Ends Logging", CanAddToTestPlan = true)]
	public bool EndLogging()
	{
		try
		{
			base.Env.DebugMessage.EndLogging();
			return true;
		}
		catch
		{
			return false;
		}
	}

	[QTMTest(Description = "Clears current tree result", CanAddToTestPlan = true)]
	public bool ClearTreeResult()
	{
		try
		{
			base.Env.DebugMessage.ClearGlobalTreeResult();
			return true;
		}
		catch
		{
			return false;
		}
	}

	[QTMParameter(ArgumentName = "fileName", DefaultValue = "TPL")]
	[QTMParameter(ArgumentName = "tplWindowName", DefaultValue = "TPL")]
	[QTMParameter(ArgumentName = "addCurrTimeToFileName", DefaultValue = "Yes", DisplayHint = DisplayHints.YESNO)]
	[QTMTest(CanAddToTestPlan = true)]
	[QTMParameter(ArgumentName = "filePath", DefaultValue = "C:\\QUALCOMM\\QSPR\\TestLog\\TPL")]
	public bool SaveTPLToFile(string fileName, string filePath, string tplWindowName, bool addCurrTimeToFileName)
	{
		if (!Directory.Exists(filePath))
		{
			Directory.CreateDirectory(filePath);
		}
		fileName = (addCurrTimeToFileName ? (fileName + "_" + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss_fff")) : fileName);
		string fileName2 = Path.Combine(filePath, fileName);
		base.Env.DebugMessage.TPLSaveToFile(tplWindowName, fileName2);
		return true;
	}

	[QTMParameter(ArgumentName = "MutexName", DefaultValue = "QSPR_Mutex", Description = "The name of the system level mutex to create/lock.")]
	[QTMParameter(ArgumentName = "WaitTimeOut", DefaultValue = "-1", Description = "How long to wait to acquire the mutex lock. A value of -1 means wait indefinitely. If the mutex is not acquired before the timeout, the test returns failure.", UnitOfMeasure = "ms")]
	[QTMParameter(ArgumentName = "ReleaseOnStopAbort", DefaultValue = "False", Description = "If true, the mutex lock will be released if QSPR is stopped/aborted.")]
	[QTMParameter(ArgumentName = "LockTimeOut", DefaultValue = "-1", Description = "The max time to hold the mutex lock. A value of -1 means the lock will be held indefinitely until UnlockMutex is called or the process dies.", UnitOfMeasure = "ms")]
	[QTMTest(Description = "Tries to lock the system level mutex with the specified name. The mutex will remain locked until UnlockMutex is called, the LockTimeOut expires, or the process dies.", CanAddToTestPlan = true)]
	public bool LockMutex(string MutexName, int WaitTimeOut, int LockTimeOut, bool ReleaseOnStopAbort)
	{
		try
		{
			return GlobalMutex.LockMutex(MutexName, WaitTimeOut, LockTimeOut, ReleaseOnStopAbort);
		}
		catch (Exception)
		{
			return false;
		}
	}

	[QTMTest(Description = "Unlock the system level mutex with the specified name.", CanAddToTestPlan = true)]
	[QTMParameter(ArgumentName = "MutexName", DefaultValue = "QSPR_Mutex", Description = "The name of the system level mutex to unlock.")]
	public bool UnlockMutex(string MutexName)
	{
		GlobalMutex.UnlockMutex(MutexName);
		return true;
	}
}
