using System;
using System.Data.SqlClient;
using System.Windows.Forms;
using QC.QTMDotNetKernelInterface;

namespace QC.QTMToolKit.Tools.Databasetools;

[QTMTestClass]
public class GetUnitStatusFromDB
{
	[QTMParameter(ArgumentName = "UnitStatus", Description = "Unit status \n -3:Unknown exception \n -2: Input parameter not in correct format \n 0: Serial Number not found in Database \n 1: Failed \n 2:Passed")]
	[QTMParameter(ArgumentName = "LastVisitOnly", Description = "Only Looks at the LastVisit of the Unit", DefaultValue = "False")]
	[QTMParameter(ArgumentName = "SerialNumber", Description = "Serial number of the unit")]
	[QTMParameter(ArgumentName = "Server", DefaultValue = "UNDP-SQL\\SQL2K8", Description = "Name of the Server")]
	[QTMParameter(ArgumentName = "TesterID", Description = "TesterID of the unit")]
	[QTMParameter(ArgumentName = "Database", DefaultValue = "QTMDB_UNDP", Description = "Name of QTM Database")]
	[QTMTest(true, "Gets the unit status for the given serial number,testerid and visitnumber combination")]
	public bool GetUnitStatus(string Server, string Database, string SerialNumber, string TesterID, bool LastVisitOnly, out int UnitStatus)
	{
		bool result = true;
		UnitStatusOutputType unitStatusOutputType = (UnitStatusOutputType)(UnitStatus = -3);
		try
		{
			if (string.IsNullOrEmpty(SerialNumber) || string.IsNullOrEmpty(TesterID) || string.IsNullOrEmpty(Server) || string.IsNullOrEmpty(Database))
			{
				unitStatusOutputType = UnitStatusOutputType.BadInput;
				return false;
			}
			string text = "GlobalResult";
			string connectionString = "workstation id=" + Server + ";packet size=4096;user id=QDMAppUser;data source=" + Server + ";persist security info=True;initial catalog=" + Database + ";password=Qual1234$";
			using (SqlConnection sqlConnection = new SqlConnection(connectionString))
			{
				sqlConnection.Open();
				string cmdText = ((!LastVisitOnly) ? string.Format("select {2} from viewSessionUnitInfov2 where UUT_SN = '{0}' and TesterID = '{1}'", SerialNumber, TesterID, text) : string.Format("select {2} from viewSessionUnitInfov2 where UUT_SN = '{0}' and TesterID = '{1}' and LastVisit = 1", SerialNumber, TesterID, text));
				SqlCommand sqlCommand = new SqlCommand(cmdText, sqlConnection);
				SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
				bool flag = false;
				if (sqlDataReader.HasRows)
				{
					while (sqlDataReader.Read())
					{
						string text2 = sqlDataReader[text].ToString();
						flag = text2.ToLower() == "passed" || flag;
					}
					unitStatusOutputType = ((!flag) ? UnitStatusOutputType.Failed : UnitStatusOutputType.Passed);
				}
				else
				{
					unitStatusOutputType = UnitStatusOutputType.SerialNumberNotFound;
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			unitStatusOutputType = UnitStatusOutputType.Unknown;
			MessageBox.Show(ex.Message);
			return false;
		}
		finally
		{
			UnitStatus = (int)unitStatusOutputType;
		}
	}
}
