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;
using AIOAIONet;

namespace PCIe_AIO16_16F
{
    public partial class EasyADCForm : Form
    {
        private UInt64 iBoardMax=0;

        public EasyADCForm()
        {
            InitializeComponent();
        }

        private void EasyADCForm_Load(object sender, EventArgs e)
        {
            if (ListDetectedBoards()) AcquireButton.Enabled = true;
        }

        private bool ListDetectedBoards()
        {
            iBoardMax = AIOAIO.BRD_GetHighestBoardIndex();
            if (AIOAIO.biNone == iBoardMax)
            {
                NumberOfDetectedBoards.Text = "No compatible devices were detected.";
                return false;
            }
            else
                if (0 == iBoardMax)
                    NumberOfDetectedBoards.Text = (iBoardMax + 1).ToString() + " compatible device was detected.";
                else
                    NumberOfDetectedBoards.Text = (iBoardMax + 1).ToString() + " compatible devices were detected."
            ;
            DeviceListBox.Items.Clear();
            for (UInt64 iBoard = 0; iBoard <= iBoardMax; iBoard++)
            {
                AIOAIO.BRD_GetName(iBoard, out string name);
                DeviceListBox.Items.Add(iBoard.ToString() + "=" + name );
            }
            if (iBoardMax != AIOAIO.biNone )
                DeviceListBox.SelectedIndex = 0
            ;
            return true;
        }

        private void AcquireButton_Click(object sender, EventArgs e)
        {
            double[] data = new double[16];
            UInt64 iBoard = (UInt64) DeviceListBox.SelectedIndex;

            AIOAIO.BRD_Reset(iBoard);

            AIOAIO.ADC_GetImmediateScanV(iBoard, data, AIOAIO.Range.Bipolar10);

            ADCResultTextBox.Clear();

            for (UInt32 ch = 0; ch < 8; ch++)
            {
                ADCResultTextBox.Text += $"ADC Ch {ch,2} = {data[ch],9:F6} Volts\tADC Ch {ch+8,2} = {data[ch+8],9:F6} Volts"+"\r\n";
            }
        }

        private void DeviceListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            AcquireButton.Enabled = DeviceListBox.SelectedIndex >= 0;
        }

        private void AcquireContinually_CheckedChanged(object sender, EventArgs e)
        {
            timer1.Enabled = AcquireContinually.Checked;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            AcquireButton_Click(sender, e);
        }
    }
}