using System;
using DebugToolInstrumentInterface;

namespace SimplePowerSupply;

[SupportedResourceName("SCPI")]
[SupportedResourceName("Simulator")]
[SupportedResourceName("Keithley_2303")]
public class PS : IPowerSupply, Instrument, IDisposable
{
	private enum PSType
	{
		Keithley_2303,
		SCPI,
		Simulator,
		Unknown
	}

	private TE_Handle te_handle;

	private Random r;

	private PSType ps;

	public void setupTEDriverType(TEDriverType type)
	{
		te_handle.SetupDriverType(type);
	}

	public PS()
	{
		te_handle = new TE_Handle();
	}

	public void Dispose()
	{
	}

	public bool Setup(string resourceString)
	{
		try
		{
			string[] array = resourceString.Split(',');
			if (array[0] == "Keithley_2303")
			{
				ps = PSType.Keithley_2303;
			}
			else if (array[0] == "SCPI")
			{
				ps = PSType.SCPI;
			}
			else if (array[0] == "Simulator")
			{
				ps = PSType.Simulator;
			}
			else
			{
				ps = PSType.Unknown;
			}
			return te_handle.Init(array[1]);
		}
		catch
		{
			return false;
		}
	}

	public void SetCurrentLimit(double limitA)
	{
		if (ps != PSType.Simulator)
		{
			string text = "";
			if (ps == PSType.Keithley_2303)
			{
				text = "CURR ";
			}
			if (ps == PSType.SCPI)
			{
				text = ":CURR ";
			}
			text += limitA;
			te_handle.write(text);
		}
	}

	public double GetResult(string query)
	{
		double num = 0.0;
		te_handle.write(query);
		string retStr = "";
		te_handle.read(out retStr);
		return Convert.ToDouble(retStr);
	}

	public double GetCurrent()
	{
		double result = 0.0;
		string text = "";
		if (ps == PSType.Keithley_2303 || ps == PSType.SCPI)
		{
			text = ":MEAS:CURR?";
			result = GetResult(text);
		}
		if (ps == PSType.Simulator)
		{
			int num = r.Next(0, 1000);
			result = (double)num / 1000.0;
		}
		return result;
	}

	public void SetVoltage(double dVolt)
	{
		string cmd = "";
		if (ps != PSType.Simulator)
		{
			if (ps == PSType.Keithley_2303 || ps == PSType.SCPI)
			{
				cmd = "VOLT ";
				cmd += dVolt;
			}
			te_handle.write(cmd);
		}
	}

	public void TurnOnOff(bool OnOff)
	{
		string cmd = "";
		if (ps != PSType.Simulator)
		{
			if (ps == PSType.Keithley_2303)
			{
				cmd = ((!OnOff) ? ":INST:STAT 0" : ":INST:STAT 1");
			}
			else if (ps == PSType.SCPI)
			{
				cmd = ((!OnOff) ? "OUTP OFF" : "OUTP ON");
			}
			te_handle.write(cmd);
		}
	}

	public string GetDriverVersion()
	{
		return typeof(PS).Assembly.GetName().Version.ToString();
	}

	public void Close()
	{
		te_handle.Close();
	}
}
