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

namespace iSTP_Embedded
{
    public partial class EmbeddedWnd : Form
    {
        private EmbeddedController _Controller;

        public EmbeddedWnd()
        {
            InitializeComponent();

            //this.comboBox1.SelectedIndex = 0;
            this.BaudRateList.SelectedItem = "8000000";
            //this.comboBox2.SelectedIndex = 0;
            this.comboBox2.SelectedItem = "8";
            //this.comboBox3.SelectedIndex = 0;
            this.comboBox3.SelectedItem = "1";
            //this.comboBox4.SelectedIndex = 0;
            this.comboBox4.SelectedItem = "None";
            this.FlowCtrlComboBox.SelectedItem = "RTS";

        }

        public void setController(EmbeddedController controller) 
        {
            this._Controller = controller;
        }

        /*
        public Boolean getAutoconnect 
        {
            get { return (this.AutoConnectButton.Checked); }
        }
        */

        public String getPort
        {
            get { return (this.COMportList.SelectedItem == null ? "None" : this.COMportList.SelectedItem.ToString()); }
        }

        public String getBaudrate
        {
            get { return (this.BaudRateList.SelectedItem.ToString()); }
        }

        public String getDatabits
        {
            get { return (this.comboBox2.SelectedItem.ToString()); }
        }

        public String getStopbits
        {
            get { return (this.comboBox3.SelectedItem.ToString()); }
        }

        public String getParity
        {
            get { return (this.comboBox4.SelectedItem.ToString()); }
        }

        public String getFlowCtrl
        {
            get { return (this.FlowCtrlComboBox.SelectedItem.ToString()); }
        }

        public UInt16 getSampleRate
        {
            get { return(Convert.ToUInt16(this.SampleRateUpDown.Value));}
        }

        public UInt16 getFifoReadRate
        {
            get { return (Convert.ToUInt16(this.FifoReadRateUpDown.Value)); }
        }

        public bool getReconfigurationRequired
        {
            get { return checkBoxReconfiguration.Checked; }
        }

        private void iSTP_EmbeddedCfg_Load(object sender, EventArgs e)
        {
            if (this.COMportList.Items.Count == 0) {
                this.COMportList.Items.Clear();
                this.COMportList.Items.AddRange(this._Controller.getAvailableCOMs());
            }

            if (this._Controller.isConfigured)
            {
                //next 3 lines added when commenting (disabling) Auto connect and Manual connect radio buttons code`
                this.COMportList.Enabled = false;
                this.BaudRateList.Enabled = false;
                this.FlowCtrlComboBox.Enabled = false;

                ConnectionGroupBox.Enabled = true;
                ConfigurationGoupBox.Enabled = true;
                this.SubmitButton.Text = "Disconnect";
            }
            else 
            {
                //this.AutoConnectButton_CheckedChanged(this, null);
                //next 3 lines added when commenting (disabling) Auto connect and Manual connect radio buttons code
                this.COMportList.Enabled = true;
                this.BaudRateList.Enabled = true;
                this.FlowCtrlComboBox.Enabled = true;

                ConnectionGroupBox.Enabled = true;
                ConfigurationGoupBox.Enabled = true;
                this.SubmitButton.Text = "Connect";
            }
            UpdateStatusBar(_Controller.StatusMessage);
        }

        public void UpdateStatusBar(string statusMsg)
        {
            this.toolStripStatusLabel1.Text = statusMsg;
        }
        
        /*
        private void ManualConnectButton_CheckedChanged(object sender, EventArgs e)
        {
            if (this.ManualConnectButton.Checked == true)
            {   
                this.COMportList.Enabled = true;
                this.BaudRateList.Enabled = true;
                this.FlowCtrlComboBox.Enabled = true;
            }
            else 
            {
                this.COMportList.Enabled = false;
                this.BaudRateList.Enabled = false;
                this.FlowCtrlComboBox.Enabled = false;
            }
        }
        */

        private void SubmitButton_Click(object sender, EventArgs e)
        {
                _Controller.ConnectAndConfigure();
        }

        /*
        private void AutoConnectButton_CheckedChanged(object sender, EventArgs e)
        {
            if (this.AutoConnectButton.Checked == true)
            {
                String port = this._Controller.getISTPport();
                if (this.COMportList.Items.Contains(port))
                    this.COMportList.SelectedItem = port;
            }
        }
        */
 
        private void EmbConfigUITimer_Tick(object sender, EventArgs e)
        {
            UpdateStatusBar(_Controller.StatusMessage);
            if (_Controller.isConfigured)
            {
                this.SubmitButton.Text = "Disconnect";
                this.SubmitButton.Enabled = true;
                ConfigurationGoupBox.Enabled = true;
                ConnectionGroupBox.Enabled = false;
            }
            
            if (_Controller.Status == EmbeddedController.PlatformStatus.FetchingConfig)
            {
                ConnectionGroupBox.Enabled = false;
                ConfigurationGoupBox.Enabled = false;
            }

            if (_Controller.Status == EmbeddedController.PlatformStatus.Error)
            {
                ConnectionGroupBox.Enabled = true;
                ConfigurationGoupBox.Enabled = false;
            }
        }

        public void SetForConnect() {
            iSTP_EmbeddedCfg_Load(this, null);
        }
        
        /*
        public void SetForConnect()
        { 
            //this.AutoConnectButton_CheckedChanged(this, null);
            ConnectionGroupBox.Enabled = true;
            ConfigurationGoupBox.Enabled = false;
            this.SubmitButton.Text = "Connect";

        }
        */

        private void close_btn_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _Controller.PowerSensors(true);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            _Controller.PowerSensors(false);
        }

        public void AddAxis(string axis)
        {
            SensorConfigTreeView.Invoke(new MethodInvoker(delegate { SensorConfigTreeView.Nodes.Add(new EmbeddedTreeNode(axis));}));
        }

        public void AddBoard(int axis, string board)
        {
            SensorConfigTreeView.Invoke(new MethodInvoker(delegate { SensorConfigTreeView.Nodes[axis].Nodes.Add(new EmbeddedTreeNode(board)); }));
        }

        public void AddParameter(int axis, int board, string param, int selectedOption)
        {
            SensorConfigTreeView.Invoke(new MethodInvoker(delegate { SensorConfigTreeView.Nodes[axis].Nodes[board].Nodes.Add(new EmbeddedTreeNode(param, axis, board, selectedOption)); }));
        }

        public  void ResetSensorView()
        {
            try
            {
                SensorConfigTreeView.Invoke(new MethodInvoker(delegate { SensorConfigTreeView.Nodes.Clear(); }));
                OptionListBox.Invoke(new MethodInvoker(delegate { OptionListBox.DataSource = null; }));
                SensorConfigure_btn.Invoke(new MethodInvoker(delegate { SensorConfigure_btn.Enabled = false; }));
            }
            catch (Exception)
            {
                return;
            }
        }

        private void SensorConfigTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            EmbeddedTreeNode node = (EmbeddedTreeNode)e.Node;
            if (node.SelectedOption >= 0)
            {
                OptionListBox.DataSource = _Controller.GetParamList(node.Axis, node.Board, node.Index);
                int _buff = _Controller.GetSelectedOption(node.Axis, node.Board, node.Index);
                if (_buff >= OptionListBox.Items.Count)
                    _buff = OptionListBox.Items.Count - 1;
                OptionListBox.SelectedIndex = _buff;
                SensorConfigure_btn.Enabled = true;
            }
            else
            {
                OptionListBox.DataSource = null;
                SensorConfigure_btn.Enabled = false;
            }
        }

        private void SensorConfigure_btn_Click(object sender, EventArgs e)
        {
            EmbeddedTreeNode node = (EmbeddedTreeNode) SensorConfigTreeView.SelectedNode;
            if (node.SelectedOption >= 0)
            {
                int paramIdx = node.Index;
                int axis = node.Axis;
                int board = node.Board;
                int optionIdx = OptionListBox.SelectedIndex;
                _Controller.ConfigureBoardParameter(axis, board, paramIdx, optionIdx);
            }
        }

        private void SimSensor_btn_Click(object sender, EventArgs e)
        {
            _Controller.SetSimSensorCount(Convert.ToUInt16(this.SimSensorCount.Value));
        }


        public void ChangeFWInfo(string version, string info)
        {
            FWInfoLbl.Invoke(new MethodInvoker(delegate { FWInfoLbl.Text = version; }));
            toolTip1.SetToolTip(FWInfoLbl, info);
        }

        public bool HealthDataRequested { get { return HealthData_CheckBox.Checked; } }

        public bool FifoModeRequested { get { return FifoMode_CheckBox.Checked; } }

        private void FifoMode_CheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (FifoMode_CheckBox.Checked)
            {
                FifoReadRateUpDown.Enabled = true;
            }
            else
            {
                FifoReadRateUpDown.Enabled = false;
            }
        }

        private void COMreloadButton_Click(object sender, EventArgs e)
        {
            this.COMportList.Items.Clear();
            this.COMportList.Items.AddRange(this._Controller.getAvailableCOMs());
        }
    }
    public class EmbeddedTreeNode : TreeNode
    {
        public int Axis;
        public int Board;
        public int SelectedOption;

        public EmbeddedTreeNode(string name, int axis = 0, int board = 0, int selectedOption = -1)
        {
            SelectedOption = selectedOption;
            Axis = axis;
            Board = board;
            this.Text = name;
        }
    }

}

