using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Rendering;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using Trio.UnifiedApi;



namespace FullFeaturesUnifiedApi_rev001
{
    public partial class Form1 : Form
    {
        private Sample _sample;
        private List<TextBox> paramTextBoxs;
        string mcIP;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            paramTextBoxs = new List<TextBox> { tbUnits, tbSpeed, tbAccel, tbDecel, tbDriveFeLimit };
            this.cbVRIdx.Items.Add("VR(0)");
            this.cbVRIdx.Items.Add("VR(1)");
            this.cbVRIdx.Items.Add("VR(2)");
            this.cbVRIdx.Items.Add("VR(3)");
            this.cbVRIdx.Items.Add("VR(4)");
            this.cbVRIdx.SelectedIndex = 0;
            this.cbTableIdx.Items.Add("Table(0)");
            this.cbTableIdx.Items.Add("Table(1)");
            this.cbTableIdx.Items.Add("Table(2)");
            this.cbTableIdx.Items.Add("Table(3)");
            this.cbTableIdx.Items.Add("Table(4)");
            this.cbTableIdx.SelectedIndex = 0;
        }
        private string checkMCIP()
        {
            // Extract the text from the text box
            var ip_entered = tbIP.Text;

            // Check if there are a valid number of IP characters
            if (ip_entered.Length < 11)  //the standard value is 11
            {
                MessageBox.Show("Not enough characters entered for a valid IP address");
                return null;
            }

            // Now check that the IP address is valid 
            var first_port = ip_entered.Substring(0, 10);
            if (first_port != "192.168.0.")  //the standard ip is : "192.168.0."
            {
                MessageBox.Show("IP address must commense with 192.168.0.");
                return null;
            }
            return ip_entered;
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                mcIP = checkMCIP();
                if (mcIP == null)
                {
                    MessageBox.Show("wrong IP format!");
                    return;
                }
                _sample?.Dispose();  //close the sample if opened before!
                //re-open the _sample with user IP
                _sample = new Sample(mcIP);

                    _sample.connectExecute();
                    if(_sample.isConnectedFLG())
                    connectionLight.BackColor = Color.Lime;
            }
            catch (TrioConnectionException ex)
            {
                MessageBox.Show($"Connection Error:{ex.Message}");
            }
            
            tbECTAState.Text = _sample.getEthercatState(0);
            _sample.AxisAlarmValueChanged += _sample_AxisAlarmValueChanged;  //axis error subscriber
        }
        //get axis alarm status in text box
        private void _sample_AxisAlarmValueChanged(object sender, Sample.driveErrorCode newAlarm)
        {
            if (tbAlarmCheck.InvokeRequired)
            {
                tbAlarmCheck.Invoke(new Action(() => tbAlarmCheck.Text = newAlarm.ToString()));
            }
            else
            {
                tbAlarmCheck.Text = newAlarm.ToString();
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            _sample?.Dispose();
        }
        private void btnWDOGON_Click(object sender, EventArgs e)
        {
            _sample.wdgCommand(true);
        }
        private void btnWDOGOFF_Click(object sender, EventArgs e)
        {
            _sample.wdgCommand(false);
        }
        private void btnSetParam_Click(object sender, EventArgs e)
        {
            if(tbUnits.Enabled != true)
            {
                foreach (var txt in paramTextBoxs)
                {
                    txt.Enabled = true;
                }
                btnSetParam.ColorTable = eButtonColor.MagentaWithBackground;
                return;
            }
            else
            {
                _sample.setAxisParam(0, double.Parse(tbUnits.Text), double.Parse(tbSpeed.Text), double.Parse(tbAccel.Text), double.Parse(tbDecel.Text), 70, 100, 10000, -10000, 100);
                btnSetParam.ColorTable = eButtonColor.OrangeWithBackground;
                foreach (var txt in paramTextBoxs)
                {
                    txt.Enabled = false;
                }

            }

        }
        private void btnGetParam_Click(object sender, EventArgs e)
        {
            var result = _sample.getAxisParam<double, double, double, double, double, long>(0);
            tbUnits.Text = result.units.ToString();
            tbDPos.Text = result.pos.ToString();
            tbSpeed.Text = result.speed.ToString();
            tbAccel.Text = result.accel.ToString();
            tbDecel.Text = result.decel.ToString();
            tbDriveFeLimit.Text = result.drive_fe_Limit.ToString();
        }
        private void btnMoveRel_Click(object sender, EventArgs e)
        {
            _sample.singleMoveRel(0,double.Parse(this.tbPos.Text));
        }
        private void btnABSPos_Click(object sender, EventArgs e)
        {
            _sample.singleMoveAbs(0, double.Parse(this.tbPos.Text));
        }
        private void btnECATRUN_Click(object sender, EventArgs e)
        {
            _sample.ethercatStartCommand(0, 3000);
            tbECTAState.Text = _sample.getEthercatState(0);


        }
        private void btnAlmRST_Click(object sender, EventArgs e)
        {
            _sample.writeTable(103, 1); //send alarm reset command
            //get back resault on table(101)

        }
        private void btnAxisStatus_Click(object sender, EventArgs e)
        {
            this.tbAxisStatus.Text = _sample.getAxisStatus(0);
        }
        private void btnAlarmCheck_Click(object sender, EventArgs e)
        {
            _sample.UpdateAlarmFromDrive();
        }
        private void btnDIRead_Click(object sender, EventArgs e)
        {
            tbDIDisplay.Text = _sample.getD_IN(0).ToString();
        }
        private void btnDOWrite_Click(object sender, EventArgs e)
        {
            if(cbDO0.Checked)
                _sample.setD_OUT(0,true);
            else _sample.setD_OUT(0,false);
        }
        private void btnReadVR_Click(object sender, EventArgs e)
        {
            uint idx = uint.Parse(cbVRIdx.SelectedIndex.ToString());
            tbVRDisplay.Text = _sample.readVR(idx).ToString();
        }
        private void btnWriteVR_Click(object sender, EventArgs e)
        {
            uint idx = uint.Parse(cbVRIdx.SelectedIndex.ToString());
            _sample.writeVR(idx,double.Parse(tbSetVR.Text));
        }
        private void btnReadTable_Click(object sender, EventArgs e)
        {
            uint idx = uint.Parse(cbTableIdx.SelectedIndex.ToString());
            tbTableDisplay.Text = _sample.readTable(idx).ToString();
        }
        private void btnWriteTable_Click(object sender, EventArgs e)
        {
            uint idx = uint.Parse(cbTableIdx.SelectedIndex.ToString());
            _sample.writeTable(idx,double.Parse(tbSetTableValue.Text));
        }
        private void btnDefpos_Click(object sender, EventArgs e)
        {
            _sample.zeroDefPos(0);
        }
    }
}
