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

using SmartX;
using ITC81DB_2_ImageDll;
using ITC81DB_2.DialogForms;
using ITC81DB_2.Forms;

namespace ITC81DB_2.Controls
{
    public partial class ControlCenterConfiEthernet : UserControl
    {
        #region Field
        private static int ModeSTD2 = 4;
        private FormMenu m_ParentForm;
        private bool IsServerON;
        private bool IsAddOnVisible;

        public ControlConfiEthernetLocalIP ControlEthernetLocalIP;
        public ControlConfiModbus ControlModbusTCP;
        public ControlConfiEthernetAddon ControlEthernetAddon;

        private delegate void ConnetedIPStatusCallback(string value);
        #endregion

        #region Constructor
        public ControlCenterConfiEthernet(FormMenu parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

            this.DefaultSetting();
            this.InitializeDesign();
        }
        #endregion

        #region Property
        public FormMenu ParentForm
        {
            get { return this.m_ParentForm; }
            private set { this.m_ParentForm = value; }
        }
        #endregion

        #region Method
        public void InitializeDesign()
        {
            Class1 images = new Class1();

            this.labelTitleConnectedIP.Text = "Connceted IP";
            this.labelTitleServerPort.Text = "Port";
            this.labelTitleClientServerIP.Text = "Server IP";
            this.labelTitleClientServerPort.Text = "Server Port";

            this.buttonLocalIP.Font = new Font("새굴림", 13, FontStyle.Bold);
            this.buttonLocalIP.Text = "Local IP";
            this.buttonStart.Text = "Start";
            this.buttonStop.Text = "Stop";

            if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.English)
            {
                this.labelTitleOperationMode.Text = "Operation mode";
                this.labelTitleCommMode.Text = "Communication mode";
                this.labelTitleSetting.Text = "Setting";
                this.labelTitleSend.Text = "Send";
                this.labelTitleReceive.Text = "Receive";
                this.labelTitleServer.Text = "Server";
                this.labelTitleClient.Text = "Client";

                this.comboBoxEthernetOpMode.Items.Clear();
                this.comboBoxEthernetOpMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
                this.comboBoxEthernetOpMode.Items.Add("None");
                this.comboBoxEthernetOpMode.Items.Add("Server");
                this.comboBoxEthernetOpMode.Items.Add("Client");
                this.comboBoxEthernetOpMode.SelectedIndex = 0;
                this.comboBoxEthernetOpMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Chinese)
            {
                this.labelTitleOperationMode.Text = "运转模式";
                this.labelTitleCommMode.Text = "通信模式";
                this.labelTitleSetting.Text = "设定值";
                this.labelTitleSend.Text = "发送";
                this.labelTitleReceive.Text = "接受";
                this.labelTitleServer.Text = "Server";
                this.labelTitleClient.Text = "Client";

                this.labelTitleConnectedIP.Text = "连接的IP";
                this.labelTitleServerPort.Text = "端口";
                this.labelTitleClientServerIP.Text = "服务器IP";
                this.labelTitleClientServerPort.Text = "服务器端口";

                this.buttonLocalIP.Font = new Font("새굴림", 11, FontStyle.Bold);
                this.buttonLocalIP.Text = "设备IP地址";
                this.buttonStart.Text = "开启";
                this.buttonStop.Text = "停止";

                this.comboBoxEthernetOpMode.Items.Clear();
                this.comboBoxEthernetOpMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
                this.comboBoxEthernetOpMode.Items.Add("不使用");
                this.comboBoxEthernetOpMode.Items.Add("Server");
                this.comboBoxEthernetOpMode.Items.Add("Client");
                this.comboBoxEthernetOpMode.SelectedIndex = 0;
                this.comboBoxEthernetOpMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Czech)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Russian)
            {
                this.labelTitleOperationMode.Text = "Режим работы";
                this.labelTitleCommMode.Text = "Режим обмена";
                this.labelTitleSetting.Text = "Настройка значений";
                this.labelTitleSend.Text = "Отправить";
                this.labelTitleReceive.Text = "Получить";
                this.labelTitleServer.Text = "Сервер";
                this.labelTitleClient.Text = "Клиент";

                this.labelTitleConnectedIP.Text = "Подключенный IP";
                this.labelTitleServerPort.Text = "Порт";
                this.labelTitleClientServerIP.Text = "Сервер IP";
                this.labelTitleClientServerPort.Text = "Сервер Порт";

                this.buttonLocalIP.Font = new Font("새굴림", 13, FontStyle.Bold);
                this.buttonLocalIP.Text = "IP адрес";
                this.buttonStart.Text = "Старт";
                this.buttonStop.Text = "Стоп";

                this.comboBoxEthernetOpMode.Items.Clear();
                this.comboBoxEthernetOpMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
                this.comboBoxEthernetOpMode.Items.Add("Нет");
                this.comboBoxEthernetOpMode.Items.Add("Сервер");
                this.comboBoxEthernetOpMode.Items.Add("Клиент");
                this.comboBoxEthernetOpMode.SelectedIndex = 0;
                this.comboBoxEthernetOpMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.German)
            {
                this.labelTitleOperationMode.Text = "Betriebsmodus";
                this.labelTitleCommMode.Text = "Kommunikationsmodus";
                this.labelTitleSetting.Text = "Einstellungswert";
                this.labelTitleSend.Text = "Senden";
                this.labelTitleReceive.Text = "Erhalten";
                this.labelTitleServer.Text = "Server";
                this.labelTitleClient.Text = "Client";

                this.comboBoxEthernetOpMode.Items.Clear();
                this.comboBoxEthernetOpMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
                this.comboBoxEthernetOpMode.Items.Add("None");
                this.comboBoxEthernetOpMode.Items.Add("Server");
                this.comboBoxEthernetOpMode.Items.Add("Client");
                this.comboBoxEthernetOpMode.SelectedIndex = 0;
                this.comboBoxEthernetOpMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Spanish)
            {
                this.labelTitleOperationMode.Text = "Modo de operación";
                this.labelTitleCommMode.Text = "Modo de comunicación";
                this.labelTitleSetting.Text = "Setear Valor";
                this.labelTitleSend.Text = "Enviar";
                this.labelTitleReceive.Text = "Recibir";
                this.labelTitleServer.Text = "Servidor";
                this.labelTitleClient.Text = "Cliente";

                this.comboBoxEthernetOpMode.Items.Clear();
                this.comboBoxEthernetOpMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
                this.comboBoxEthernetOpMode.Items.Add("Ninguna");
                this.comboBoxEthernetOpMode.Items.Add("Servidor");
                this.comboBoxEthernetOpMode.Items.Add("Cliente");
                this.comboBoxEthernetOpMode.SelectedIndex = 0;
                this.comboBoxEthernetOpMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
            }
            else
            {
                this.labelTitleOperationMode.Text = "동작 모드";
                this.labelTitleCommMode.Text = "통신 모드";
                this.labelTitleSetting.Text = "설정";
                this.labelTitleSend.Text = "송신";
                this.labelTitleReceive.Text = "수신";
                this.labelTitleServer.Text = "Server";
                this.labelTitleClient.Text = "Client";

                this.comboBoxEthernetOpMode.Items.Clear();
                this.comboBoxEthernetOpMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
                this.comboBoxEthernetOpMode.Items.Add("None");
                this.comboBoxEthernetOpMode.Items.Add("Server");
                this.comboBoxEthernetOpMode.Items.Add("Client");
                this.comboBoxEthernetOpMode.SelectedIndex = 0;
                this.comboBoxEthernetOpMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);
            }
        }
        private void DefaultSetting()
        {
            string[] sValue;

            this.IsServerON = false;
            this.IsAddOnVisible = false;

            this.ControlEthernetLocalIP = new ControlConfiEthernetLocalIP(this.ParentForm);
            this.Controls.Add(this.ControlEthernetLocalIP);
            this.ControlEthernetLocalIP.Location = new Point(0, 217);

            this.ControlModbusTCP = new ControlConfiModbus(this.ParentForm);
            this.Controls.Add(this.ControlModbusTCP);
            this.ControlModbusTCP.Location = new Point(0, 217);

            this.ControlEthernetAddon = new ControlConfiEthernetAddon(this.ParentForm);
            this.Controls.Add(this.ControlEthernetAddon);
            this.ControlEthernetAddon.Location = new Point(0, 217);

            this.ControlVisible(false);

            if (this.ParentForm.ParentForm.SystemConfig.IsEthernetEnable == true)
            {
                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = true;
            }
            else
            {
                this.buttonStart.Enabled = false;
                this.buttonStop.Enabled = false;
            }

            this.labelServerStatus.Text = "-";
            this.labelClientStatus.Text = "-";
            this.labelConnectedIP.Text = "-";

            // Host IP
            sValue = this.ParentForm.ParentForm.SystemConfig.EthernetAddress.Split('.');
            this.labelHostIP1.Text = sValue[0];
            this.labelHostIP2.Text = sValue[1];
            this.labelHostIP3.Text = sValue[2];
            this.labelHostIP4.Text = sValue[3];

            this.labelHostPort.Text = this.ParentForm.ParentForm.SystemConfig.EthernetHostPort.ToString();
            this.labelLocalPort.Text = this.ParentForm.ParentForm.SystemConfig.EthernetLocalPort.ToString();

            this.ChangeCommunicationMode();

            this.buttonSaveClient.Enabled = false;
        }
        public void ChangeCommunicationMode()
        {
            this.comboBoxEthernetMode.Items.Clear();
            this.comboBoxEthernetMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetMode_SelectedIndexChanged);

            this.comboBoxEthernetMode.Items.Add("None");
            this.comboBoxEthernetMode.Items.Add("STD1");
            this.comboBoxEthernetMode.Items.Add("Remote");
            this.comboBoxEthernetMode.Items.Add("Printer");
            this.comboBoxEthernetMode.Items.Add("STD2"); // STD2
            this.comboBoxEthernetMode.Items.Add("imaje 9028 OPT2"); // 한맥

            this.comboBoxEthernetMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetMode_SelectedIndexChanged);
        }

        public void DisplayLabelReceive(string sValue)
        {
            this.labelReceive.Text = sValue;
        }
        public void DisplayLabelLocalPort(bool bValue)
        {
            if (bValue == false)
            {
                this.labelLocalPort.Enabled = false;
                this.labelLocalPort.BackColor = Color.Silver;
            }
            else
            {
                this.labelLocalPort.Enabled = true;
                this.labelLocalPort.BackColor = Color.White;
            }
        }
        public void UpdateEthernetStatusDisplay(string value)
        {
            if (this.labelClientStatus.Text != value)
                this.labelClientStatus.Text = value;
        }
        private void UpdateLabelFormatDisplay()
        {
            this.buttonTestSend.Enabled = true;

            switch (this.comboBoxEthernetMode.SelectedIndex)
            {
                case 1: // STD1
                    this.labelFormat.Text = "STX[1],ID[5],No[4],Lane[1],U[6],R[6],O[6],G[1],W[6],ETX[1]";
                    break;
                case 2: // Remote
                    this.labelFormat.Text = "STX[1],No[2],Grd[1],Weight[6],ETX[1]";
                    break;
                case 3: // Printer
                    this.labelFormat.Text = "No[4],Grd[8],Weight[10],CNT[10]";
                    break;
                case 4:  // STD2
                    this.labelFormat.Text = "STX[1],ID[5],No[4],Lane[1],U[6],P[6],O[6],UC[7],PC[7],OC[7],ExC[7],TC[9],Grd[1],Sign[1],Weight[6],ETX[1]";
                    break;
                case (int)Define.E_CommMode.f5_imaje_9028_OPT2: // imaje_9028_OPT2
                    this.labelFormat.Text = "ENQ ->(30ms) 0x99, 0x00, 0x07, 0x12, Weight[5], 0x12, Checksum[1]";
                    break;
                default:
                    break;
            }
        }
        public void DisplayHiddenMenu(bool bValue)
        {
            if (bValue == true)
            {
                this.buttonPingTimer.Visible = true;
            }
            else
            {
                this.buttonPingTimer.Visible = false;
            }
        }

        private void ControlVisible(bool visible)
        {
            this.ControlModbusTCP.Visible = visible;
            this.ControlEthernetAddon.Visible = visible;
        }
        private void DisplayBottomSettingMenu()
        {
            this.ControlVisible(false);

            this.buttonTestSend.Enabled = true;

            if (this.comboBoxEthernetMode.SelectedIndex == (int)Define.E_CommMode.f99_Modbus&& this.ParentForm.ParentForm.SystemConfig.IsModbus == true)
            {
                this.ControlModbusTCP.DisplayRefresh(this.ParentForm.CurrentConfigurationMenu());
                this.ControlModbusTCP.Visible = true;
                this.ControlModbusTCP.BringToFront();
            }
            else
            {
                this.ControlEthernetAddon.DisplayRefresh();
                this.ControlEthernetAddon.Visible = true;
                this.ControlEthernetAddon.BringToFront();
            }
        }

        private void ConnectedIPStatusOut(string value)
        {
            this.labelConnectedIP.Text = value;
        }
        public void DelegateConnectedIPStatusOut(string value)
        {
            this.Invoke(new ConnetedIPStatusCallback(this.ConnectedIPStatusOut), value);
        }

        public void DisplayRefresh(SystemStatus status)
        {
            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplay = Define.E_DisplayStore.ConfiEthernet;
            this.ParentForm.ParentForm.SetDisplayMode(Define.E_DisplayMode.Menu);
            this.ParentForm.DisplayTitleRoot(this.ParentForm.ParentForm.CurrentSystemStatus);

            this.comboBoxEthernetMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetMode_SelectedIndexChanged);
            this.comboBoxEthernetOpMode.SelectedIndexChanged -= new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);

            this.comboBoxEthernetOpMode.SelectedIndex = this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode;
            this.comboBoxEthernetMode.SelectedIndex = this.ParentForm.ParentForm.SystemConfig.EthernetCommMode;

            this.comboBoxEthernetMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetMode_SelectedIndexChanged);
            this.comboBoxEthernetOpMode.SelectedIndexChanged += new EventHandler(this.comboBoxEthernetOpMode_SelectedIndexChanged);

            this.UpdateLabelFormatDisplay();

            this.DisplayHiddenMenu(false);
            if (this.ParentForm.ParentForm.SystemConfig.IsEthernetPingTimer == true)
            {
                this.buttonPingTimer.Text = "Ping Close";
                this.buttonPingTimer.ButtonDown();
            }
            else
            {
                this.buttonPingTimer.Text = "Ping Open";
                this.buttonPingTimer.ButtonUp();
            }

            if (this.comboBoxEthernetOpMode.SelectedIndex == 1)
            {
                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = true;

                if (string.Compare(this.ParentForm.ParentForm.smartConfigs.IPSettings.DeviceIP, "0.0.0.0") == 0)
                {
                    if (this.labelServerStatus.Text != ">Addr Err")
                        this.labelServerStatus.Text = ">Addr Err";

                    this.timerServer.Enabled = false;
                }
                else
                {
                    this.ParentForm.ParentForm.EthernetServerStart();

                    if (this.timerServer.Enabled != true)
                        this.timerServer.Enabled = true;
                }
            }
            else if (this.comboBoxEthernetOpMode.SelectedIndex == 2)
            {
                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = true;

                this.ParentForm.ParentForm.EthernetClientConnect();
            }
            else
            {
                this.buttonStart.Enabled = false;
                this.buttonStop.Enabled = false;

                this.labelServerStatus.Text = "-";
                this.labelClientStatus.Text = "-";
                this.labelConnectedIP.Text = "-";
            }
            this.labelLocalPort.Text = this.ParentForm.ParentForm.SystemConfig.EthernetLocalPort.ToString();

            this.buttonSave.Enabled = false;
        }
        #endregion

        #region Event Handler
        private void buttonClientStart_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.EthernetClientConnect();
        }
        private void buttonClientStop_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.EthernetClientDisconnect();
        }
        private void buttonTestSend_Click(object sender, EventArgs e)
        {
            int tempStringLength = 0;
            string tempString = "";
            string str = "";
            bool isFillZero = this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroEthernet;

            StringBuilder sb = new StringBuilder();
            byte[] byteArray = new byte[12];
            byte[] weightBytes = new byte[4];
            byte[] bytes = new byte[100];

            if (this.comboBoxEthernetMode.SelectedIndex == 0)
                return;

            switch (this.comboBoxEthernetMode.SelectedIndex)
            {
                case 1:
                    #region STD1
                    sb.Append((char)0x02);
                    sb.Append("IN001");
                    sb.Append("0001");
                    sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("1000", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("2000", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("3000", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append("P");
                    sb.Append(" ");
                    sb.Append(string.Format("{0, 6}", Helper.DoubleToString(123.4, this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append((char)0x03);
                    #endregion
                    break;
                case 2:
                    #region Remote
                    sb.Append((char)0x02);
                    sb.Append("01");
                    sb.Append("P");
                    sb.Append("0");
                    sb.Append(Helper.StringToDecimalPlaces("1234", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces));
                    sb.Append((char)0x03);
                    #endregion
                    break;
                case 3:
                    #region Printer
                    sb.Append("0001");
                    sb.Append("    Pass");
                    sb.Append(this.ParentForm.ParentForm.PadLeft(9, Helper.DoubleToString
                                    (this.ParentForm.ParentForm.CurrentWeightData1.Weight, this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append(" ");
                    sb.Append("1234567890");
                    //sb.Append(Helper.StringZeroFillDigits4(this.ParentForm.ParentForm.CurrentProductItem1.Number.ToString()));
                    //sb.Append("   Empty");
                    //sb.Append(this.ParentForm.ParentForm.PadLeft(10, Helper.DoubleToString
                    //    (this.ParentForm.ParentForm.CurrentWeightData.Weight, this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    //sb.Append("Balance".PadLeft(10, ' '));
                    #endregion
                    break;
                case 4:
                    #region STD2
                    sb.Append((char)0x02);
                    sb.Append("IN001");
                    sb.Append("0001");
                    sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("1000", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("2000", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("3000", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append(string.Format("{0:0000000}", 11111));
                    sb.Append(string.Format("{0:0000000}", 22222));
                    sb.Append(string.Format("{0:0000000}", 33333));
                    sb.Append(string.Format("{0:0000000}", 11111));
                    sb.Append(string.Format("{0:000000000}", 77777));
                    sb.Append("P");
                    sb.Append(" ");
                    sb.Append(Helper.StringZeroFillDigits6(Helper.DoubleToString(123.4, this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append((char)0x03);
                    #endregion
                    break;
                case (int)Define.E_CommMode.f99_Modbus:
                    #region Modbus TCP(16. Write Multiple Registers)
                    if (this.ParentForm.ParentForm.SystemConfig.IsModbus == true)
                    {
                        if (this.ParentForm.ParentForm.SystemConfig.ModbusTCPSelectFunction == (int)Define.E_ModbusFunction._16_WriteMultipleRegister)
                        {
                            byte[] sendData = this.ParentForm.ParentForm.Modbus.MakeTCPSendAllData(this.ParentForm.ParentForm.Transfer_5_Modbus_Write_1Lane(), this.ParentForm.ParentForm.SystemConfig.ModbusTCPStartAddress);

                            this.ParentForm.ParentForm.EthernetWeightDataForModbus(sendData);
                        }
                    }
                    #endregion
                    break;
                default:
                    break;
            }

            switch (this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode)
            {
                case 1:

                    if (this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList != null)
                    {
                        foreach (SmartTCPMultiServer.CLIENTSINFOS client in this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList)
                        {
                            if (sb.ToString() == "")
                                this.ParentForm.ParentForm.EthernetServerSendMessage(client, byteArray);
                            else
                                this.ParentForm.ParentForm.EthernetServerSendMessage(client, sb.ToString());
                        }
                    }
                    break;
                case 2:
                    if (sb.ToString() == "")
                        this.ParentForm.ParentForm.EthernetWeightData(byteArray);
                    else
                        this.ParentForm.ParentForm.EthernetWeightData(sb.ToString());
                    break;
                default:
                    break;
            }
        }
        private void buttonSave2_Click(object sender, EventArgs e)
        {
            string beforeServerIP = "", afterServerIP = "";
            string beforeServerPort = "", afterServerPort = "";

            beforeServerIP = this.ParentForm.ParentForm.SystemConfig.EthernetAddress;
            beforeServerPort = this.ParentForm.ParentForm.SystemConfig.EthernetHostPort.ToString();
            try
            {
                this.ParentForm.ParentForm.SystemConfig.EthernetHostPort = int.Parse(this.labelHostPort.Text);
                afterServerPort = this.ParentForm.ParentForm.SystemConfig.EthernetHostPort.ToString();
            }
            catch
            {
                this.ParentForm.ParentForm.SystemConfig.EthernetHostPort = 0;
                afterServerPort = "0";
            }

            this.ParentForm.ParentForm.SystemConfig.EthernetAddress = string.Format("{0}.{1}.{2}.{3}",
                this.labelHostIP1.Text, this.labelHostIP2.Text, this.labelHostIP3.Text, this.labelHostIP4.Text);

            afterServerIP = this.ParentForm.ParentForm.SystemConfig.EthernetAddress;

            this.ParentForm.ParentForm.SaveSystemConfigurationFile2(this.ParentForm.ParentForm.SystemConfig);
            this.ParentForm.ParentForm.EthernetClientDisconnect();
            this.buttonSaveClient.Enabled = false;

            //if (beforeServerIP != afterServerIP)
            //    this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingParameter.TCPServerIPAddress, "", beforeServerIP, afterServerIP);
            //if (beforeServerPort != afterServerPort)
            //    this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingParameter.TCPServerPort, "", beforeServerPort, afterServerPort);
        }

        private void labelHostPort_Click(object sender, EventArgs e)
        {
            DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelHostPort.Text, 5, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

            if (myKeyPad.ShowDialog() == DialogResult.OK)
            {
                this.labelHostPort.Text = myKeyPad.StringValue;
                this.buttonSaveClient.Enabled = true;
            }
        }
        private void labelHostIP1_Click(object sender, EventArgs e)
        {
            string temp = "";

            DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelHostIP1.Text, 3, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

            if (myKeyPad.ShowDialog() == DialogResult.OK)
            {
                if (myKeyPad.IntValue > 255)
                {
                    temp = "0 ~ 255";
                    DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language, temp);
                    myMsg.ShowDialog();
                }
                else
                {
                    this.labelHostIP1.Text = myKeyPad.StringValue;
                    this.buttonSaveClient.Enabled = true;
                }
            }
        }
        private void labelHostIP2_Click(object sender, EventArgs e)
        {
            string temp = "";

            DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelHostIP2.Text, 3, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

            if (myKeyPad.ShowDialog() == DialogResult.OK)
            {
                if (myKeyPad.IntValue > 255)
                {
                    temp = "0 ~ 255";
                    DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language, temp);
                    myMsg.ShowDialog();
                }
                else
                {
                    this.labelHostIP2.Text = myKeyPad.StringValue;
                    this.buttonSaveClient.Enabled = true;
                }
            }
        }
        private void labelHostIP3_Click(object sender, EventArgs e)
        {
            string temp = "";

            DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelHostIP3.Text, 3, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

            if (myKeyPad.ShowDialog() == DialogResult.OK)
            {
                if (myKeyPad.IntValue > 255)
                {
                    temp = "0 ~ 255";
                    DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language, temp);
                    myMsg.ShowDialog();
                }
                else
                {
                    this.labelHostIP3.Text = myKeyPad.StringValue;
                    this.buttonSaveClient.Enabled = true;
                }
            }
        }
        private void labelHostIP4_Click(object sender, EventArgs e)
        {
            string temp = "";

            DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelHostIP4.Text, 3, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

            if (myKeyPad.ShowDialog() == DialogResult.OK)
            {
                if (myKeyPad.IntValue > 255)
                {
                    temp = "0 ~ 255";
                    DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language, temp);
                    myMsg.ShowDialog();
                }
                else
                {
                    this.labelHostIP4.Text = myKeyPad.StringValue;
                    this.buttonSaveClient.Enabled = true;
                }
            }
        }

        private void timerServer_Tick(object sender, EventArgs e)
        {
            if (this.ParentForm.ParentForm.smartTCPMultiServer.IsStart == true)
            {
                if (this.labelServerStatus.Text != ">Start")
                    this.labelServerStatus.Text = ">Start";

                if (this.IsServerON == false)
                {
                    this.IsServerON = true;
                    //this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.ServerON, "");
                }

                this.smartListBoxClientList.ClearAll();
                this.labelClientCount.Text = "-";
                this.labelConnectedIP.Text = "-";

                if (this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList != null)
                {
                    int length = this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList.Length;
                    for (int i = 0; i < length; i++)
                    {
                        this.smartListBoxClientList.AddItem(
                            this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList[i].strID + ", " +
                            this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList[i].strIPAddress);
                    }

                    this.labelClientCount.Text = length.ToString();
                    if (this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList == null)
                        this.labelConnectedIP.Text = "-";
                    else
                        this.labelConnectedIP.Text = this.ParentForm.ParentForm.smartTCPMultiServer.ClientInfoList[0].strIPAddress;
                }
            }
            else
            {
                if (this.labelServerStatus.Text != ">Stop")
                    this.labelServerStatus.Text = ">Stop";

                if (this.IsServerON == true)
                {
                    this.IsServerON = false;
                    //this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.ServerOFF, "");
                }

                this.smartListBoxClientList.ClearAll();
                this.labelClientCount.Text = "-";
            }
        }
        private void labelLocalPort_Click(object sender, EventArgs e)
        {
            string before = "", after = "";
            before = this.labelLocalPort.Text;
            DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelLocalPort.Text, 5, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

            if (myKeyPad.ShowDialog() == DialogResult.OK)
            {
                after = this.labelLocalPort.Text = myKeyPad.StringValue;
                this.ParentForm.ParentForm.SystemConfig.EthernetLocalPort = myKeyPad.IntValue;
                this.ParentForm.ParentForm.SaveSystemConfigurationFile2(this.ParentForm.ParentForm.SystemConfig);
                this.ParentForm.ParentForm.smartTCPMultiServer.Port = myKeyPad.IntValue;

                //if(before != after)
                //    this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingParameter.TCPLocalPort, "", before, after);
            }
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            string detail = "";

            if (this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode == 1)
            {
                detail = "Server";

                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = true;

                if (string.Compare(this.ParentForm.ParentForm.smartConfigs.IPSettings.DeviceIP, "0.0.0.0") == 0)
                {
                    if (this.labelServerStatus.Text != ">Addr Err")
                        this.labelServerStatus.Text = ">Addr Err";

                    if (this.timerServer.Enabled != false)
                        this.timerServer.Enabled = false;

                    this.ParentForm.ParentForm.ChildFormMainDisplay.TimerServer(false);
                }
                else
                {
                    this.ParentForm.ParentForm.EthernetServerStart();

                    if (this.timerServer.Enabled != true)
                        this.timerServer.Enabled = true;

                    this.ParentForm.ParentForm.ChildFormMainDisplay.TimerServer(true);
                }
            }
            else if (this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode == 2)
            {
                detail = "Client";

                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = true;

                this.ParentForm.ParentForm.EthernetClientConnect();
            }
            //this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.TryEthernetStart, detail);
        }
        private void buttonStop_Click(object sender, EventArgs e)
        {
            string detail = "";

            if (this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode == 1)
            {
                detail = "Server";

                this.timerServer.Enabled = false;
                this.ParentForm.ParentForm.EthernetServerStop();

                if (this.labelServerStatus.Text != ">Stop")
                    this.labelServerStatus.Text = ">Stop";

                this.ParentForm.ParentForm.ChildFormMainDisplay.TimerServer(false);
            }
            else if (this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode == 2)
            {
                detail = "Client";
                this.ParentForm.ParentForm.EthernetClientDisconnect();
            }
            //this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.TryEthernetStop, detail);
        }

        private void buttonLocalIP_Click(object sender, EventArgs e)
        {
            this.ControlEthernetLocalIP.Visible = true;
            this.ControlEthernetLocalIP.BringToFront();
            this.ControlEthernetLocalIP.DisplayRefresh();
        }

        private void buttonPingTimer_Click(object sender, EventArgs e)
        {
            if (this.buttonPingTimer.ButtonStatus == SmartButton.BUTSTATUS.DOWN)
            {
                this.ParentForm.ParentForm.SystemConfig.IsEthernetPingTimer = true;
                this.buttonPingTimer.Text = "Ping Close";
                this.ParentForm.ParentForm.IsUsingTimerEthernetPing(true);
            }
            else
            {
                this.ParentForm.ParentForm.SystemConfig.IsEthernetPingTimer = false;
                this.buttonPingTimer.Text = "Ping Open";
                this.ParentForm.ParentForm.IsUsingTimerEthernetPing(false);
            }

            this.ParentForm.ParentForm.SaveSystemConfigurationFile2(this.ParentForm.ParentForm.SystemConfig);
        }

        private void comboBoxEthernetMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.comboBoxEthernetOpMode.Enabled = true;

            this.buttonSave.Enabled = true;

            this.UpdateLabelFormatDisplay();
        }
        private void comboBoxEthernetOpMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.buttonSave.Enabled = true;
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            int mode = 0;
            string beforeLocalPort = "", afterLocalPort = "";
            string beforeOpMode = "", afterOpMode = "";
            string beforeComMode = "", afterComMode = "";

            beforeLocalPort = this.labelLocalPort.Text;
            if (this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode == 1)
                beforeOpMode = "Server";
            else if (this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode == 2)
                beforeOpMode = "Client";
            else
                beforeOpMode = "None";
            beforeComMode = this.ParentForm.ParentForm.ChildFormMenu.CenterConfiSerial.ReturnCommunicationModeName(this.ParentForm.ParentForm.SystemConfig.EthernetCommMode);

            if (this.comboBoxEthernetOpMode.SelectedIndex == 1)
            {
                this.ParentForm.ParentForm.SystemConfig.ModbusTCPSelectFunction = (int)Define.E_ModbusFunction._04_ReadInputRegister;
                this.ParentForm.ParentForm.EthernetClientDisconnect();
                this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode = 1;
                afterOpMode = "Server";

                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = true;
            }
            else if (this.comboBoxEthernetOpMode.SelectedIndex == 2)
            {
                this.ParentForm.ParentForm.SystemConfig.ModbusTCPSelectFunction = (int)Define.E_ModbusFunction._16_WriteMultipleRegister;
                this.labelServerStatus.Text = "-";
                this.timerServer.Enabled = false;
                this.ParentForm.ParentForm.EthernetServerStop();
                this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode = 2;
                this.ParentForm.ParentForm.EthernetClientDisconnect();
                afterOpMode = "Client";

                this.ParentForm.ParentForm.ChildFormMainDisplay.TimerServer(false);

                this.labelConnectedIP.Text = "-";

                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = true;
            }
            else
            {
                this.timerServer.Enabled = false;
                this.ParentForm.ParentForm.EthernetServerStop();
                this.ParentForm.ParentForm.EthernetClientDisconnect();
                this.ParentForm.ParentForm.SystemConfig.EthernetOperationMode = 0;
                afterOpMode = "None";

                this.ParentForm.ParentForm.ChildFormMainDisplay.TimerServer(false);

                this.buttonStart.Enabled = false;
                this.buttonStop.Enabled = false;

                this.labelServerStatus.Text = "-";
                this.labelClientStatus.Text = "-";
                this.labelConnectedIP.Text = "-";
            }
         
            mode = this.comboBoxEthernetMode.SelectedIndex;
            this.ParentForm.ParentForm.SystemConfig.EthernetCommMode = mode;
            afterComMode = this.ParentForm.ParentForm.ChildFormMenu.CenterConfiSerial.ReturnCommunicationModeName(mode);

            if ((this.ParentForm.ParentForm.SystemConfig.SerialCOM1Mode == (int)Define.E_CommMode.f99_Modbus
                || this.ParentForm.ParentForm.SystemConfig.SerialCOM3Mode == (int)Define.E_CommMode.f99_Modbus
                || this.ParentForm.ParentForm.SystemConfig.SerialCOM4Mode == (int)Define.E_CommMode.f99_Modbus
                || this.ParentForm.ParentForm.SystemConfig.EthernetCommMode == (int)Define.E_CommMode.f99_Modbus)
                && this.ParentForm.ParentForm.SystemConfig.IsModbus == true)
            {
                this.ParentForm.ParentForm.ChildFormMainDisplay.MainBottomModbusIconAdd(true);
            }
            else
            {
                this.ParentForm.ParentForm.ChildFormMainDisplay.MainBottomModbusIconAdd(false);
            }

            this.ParentForm.ParentForm.SaveSystemConfigurationFile2(this.ParentForm.ParentForm.SystemConfig);

            this.ParentForm.ParentForm.ChildFormMainDisplay.InitialEthernetIcon();

            this.buttonSave.Enabled = false;

            afterLocalPort = this.labelLocalPort.Text;

            //if (beforeLocalPort != afterLocalPort)
            //    this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingParameter.TCPLocalPort, "", beforeLocalPort, afterLocalPort);
            //if (beforeOpMode != afterOpMode)
            //    this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingParameter.TCPOpMode, "", beforeOpMode, afterOpMode);
            //if (beforeComMode != afterComMode)
            //    this.ParentForm.ParentForm.SetTrackingHistoryData(Define.E_TrackingParameter.TCPComMode, "", beforeComMode, afterComMode);
        }

        private void buttonAddon_Click(object sender, EventArgs e)
        {
            if (this.IsAddOnVisible == false)
            {
                this.DisplayBottomSettingMenu();
                this.IsAddOnVisible = true;
            }
            else
            {
                this.ControlVisible(false);
                this.IsAddOnVisible = false;
            }
        }
        #endregion
    }
}
