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

using System.Runtime.InteropServices;
using System.IO;
using System.IO.Ports;

using LFP_Manager.DataStructure;
using LFP_Manager.Function;
using System.Data.Entity.Infrastructure;

namespace LFP_Manager.Controls
{
    public partial class ucCommConfig : DevExpress.XtraEditors.XtraUserControl
    {
        #region EVENT

        public delegate void CloseEvent(object aConfig, bool saved);

        #endregion

        #region VARIABLES

        CommConfig Config = new CommConfig();
        public event CloseEvent OnClose = null;

        DataTable dtComport = new DataTable();
        private bool saved = false;

        #endregion

        #region CONSTRUCTORS

        public ucCommConfig()
        {
            InitializeComponent();

            CommPortLoad();

            IniLoad();
        }

        private void InitComportDataTable()
        {
            dtComport = new DataTable();
            dtComport.Columns.Add("name", typeof(string));
            dtComport.Columns.Add("name2", typeof(string));
        }

        #endregion

        #region DATA LOAD AND SAVE

        private void CommPortLoad()
        {
            bool found = false;
            int ComId = 0;

            InitComportDataTable();
            foreach (string comport in SerialPort.GetPortNames())
            {
                DataRow aRow = dtComport.NewRow();
                aRow["name"] = comport;
                dtComport.Rows.Add(aRow);
            }

            for (int i = 0; i < dtComport.Rows.Count; i++)
            {
                cbUartPort.Properties.Items.Add(dtComport.Rows[i]["name"].ToString());
            }

            if (Config.UartPort != "")
            {
                for (int i = 0; i < cbUartPort.Properties.Items.Count; i++)
                {
                    if (dtComport.Rows[i]["name"].ToString() == Config.UartPort)
                    {
                        found = true;
                        ComId = i;
                        break;
                    }
                }
            }

            if (found)
            {
                cbUartPort.SelectedIndex = ComId;
                Config.UartPort = cbUartPort.Properties.Items[ComId].ToString();
            }
            else
            {
                if (cbUartPort.Properties.Items.Count > 0)
                {
                    cbUartPort.SelectedIndex = 0;
                }
            }
        }

        private void IniLoad()
        {
            csIniControlFunction.IniLoad(Application.ExecutablePath, ref Config);

            cbUartModel.Properties.Items.Clear();
            CbSnmpModel.Properties.Items.Clear();
            foreach (string m_name in csConstData.MODEL_STR)
            {
                cbUartModel.Properties.Items.Add(m_name);
                CbSnmpModel.Properties.Items.Add(m_name);
            }
            CbModuleQty.Properties.Items.Clear();
            for (int i = 0; i < csConstData.SystemInfo.MAX_MODULE_SIZE; i++)
            {
                CbModuleQty.Properties.Items.Add(string.Format("{0}", i + 1));
            }

            switch (Config.CommType)
            {
                case csConstData.CommType.COMM_UART:
                    RbUart.Checked = true;
                    break;
                case csConstData.CommType.COMM_RS485:
                    RbRS485.Checked = true;
                    break;
                case csConstData.CommType.COMM_SNMP:
                    RbSnmp.Checked = true;
                    break;
                default:
                    RbUart.Checked = true;
                    break;
            }

            if (Config.SnmpIP == "")
               { Config.SnmpIP = teTargetIP.Text; }
            teTargetIP.Text = Config.SnmpIP;
            CbSnmpModel.SelectedIndex = Config.SnmpModelIndex;

            cbUartPort.Text = Config.UartPort;
            cbUartModel.SelectedIndex = Config.UartModelIndex;
            CbModuleQty.Text = string.Format("{0}", Config.ModuleQty);
            edRecvWaitTime.Text = string.Format("{0}", Config.RecvWaitTime);

            cbDbLogPeriod.Text = Config.DbLogPeriod.ToString();
        }

        private void IniSave()
        {
            if (RbUart.Checked)
            {
                Config.CommType = csConstData.CommType.COMM_UART;
            }
            else if (RbRS485.Checked)
            {
                Config.CommType = csConstData.CommType.COMM_RS485;
            }
            else if (RbSnmp.Checked)
            {
                Config.CommType = csConstData.CommType.COMM_SNMP;
            }

            try
            {
                Config.SnmpIP = teTargetIP.Text;
                Config.SnmpModelIndex = CbSnmpModel.SelectedIndex;

                Config.UartPort = cbUartPort.Text;
                Config.UartModelIndex = cbUartModel.SelectedIndex;
                Config.ModuleQty = Convert.ToInt32(CbModuleQty.Text);
                Config.RecvWaitTime = Convert.ToInt32(edRecvWaitTime.Text);

                Config.DbLogPeriod = Convert.ToInt32(cbDbLogPeriod.Text);

                csIniControlFunction.IniSave(Application.ExecutablePath, Config);

                saved = true;
            }
            catch (Exception)
            {
                MessageBox.Show("Save fail - Please check config", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region BUTTON EVENT
        private void btnClose_Click(object sender, EventArgs e)
        {
            OnClose?.Invoke(Config, saved);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            IniSave();
        }
        #endregion

        #region COMPONENT EVENT
        private void RbUart_CheckStateChanged(object sender, EventArgs e)
        {
            if (RbUart.Checked)
            {
                LcGroupUart.Enabled = true;
                LcGroupSnmp.Enabled = false;
                CbModuleQty.Enabled = false;
                CbModuleQty.Text = "1";
            }
        }

        private void RbRS485_CheckStateChanged(object sender, EventArgs e)
        {
            if (RbRS485.Checked)
            {
                LcGroupUart.Enabled = true;
                LcGroupSnmp.Enabled = false;
                CbModuleQty.Enabled = true;
            }
        }

        private void RbSnmp_CheckedChanged(object sender, EventArgs e)
        {
            if (RbSnmp.Checked)
            {
                LcGroupUart.Enabled = false;
                LcGroupSnmp.Enabled = true;
                CbModuleQty.Enabled = true;
                CbModuleQty.Text = "1";
            }
        }
        #endregion
    }
}
