using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Demo_CSharp
{
    public partial class Form1 : Form
    {
        VisaInstrument visaInstrument = null;
        public Form1()
        {
            InitializeComponent();
            visaInstrument = new VisaInstrument();
        }

        private void btn_connect_Click(object sender, EventArgs e)
        {
            var userDefineAddress = textBox_address.Text;
            if (userDefineAddress == string.Empty)
            {
                var addressList = visaInstrument.FindDevices();
                if(addressList.Any()==false)
                {
                    AddLog("no any device find");
                }
                foreach(var address in addressList)
                {
                    if (visaInstrument.OpenSession(address) == true)
                    {
                        visaInstrument.WriteBytes("*IDN?\n");
                        AddLog("*IDN?\n");
                        var readValue = visaInstrument.ReadBytes();
                        AddLog(readValue);
                        if (readValue.Contains("HDM"))
                        {
                            textBox_address.Text = address;
                            AddLog($"connected device {address}");
                            return;
                        }
                    }
                }
                AddLog("no any device connected");
            }
            else
            {
                var connectState = visaInstrument.OpenSession(userDefineAddress);
                if (connectState)
                {
                    AddLog($"device {userDefineAddress} connect success");
                }
                else
                {
                    AddLog($"device {userDefineAddress} connect faild");
                }
            }
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            var sendStr = $"{textBox_command.Text}\n";
            visaInstrument.WriteBytes(sendStr);
            AddLog(sendStr);
        }

        private void btn_read_Click(object sender, EventArgs e)
        {
            var readStr = visaInstrument.ReadBytes();
            AddLog(readStr);
        }

        private void btn_sendAndRead_Click(object sender, EventArgs e)
        {
            var sendStr = $"{textBox_command.Text}\n";
            visaInstrument.WriteBytes(sendStr);
            AddLog(sendStr);
            var readStr = visaInstrument.ReadBytes();
            AddLog(readStr);
        }

        private void AddLog(string logStr)
        {
            logStr = logStr.Replace("\n", "");
            var log = $"{DateTime.Now.ToString("HH:mm:ss fff")}:{logStr}\n";
            richTextBox_log.AppendText(log);
        }
    }
}
