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

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

namespace ITC81DB_2.Controls
{
    public partial class ControlCenterConfiSerial : UserControl
    {
        #region Field
        private static int ModeSTD2 = 4;

        private FormMenu m_ParentForm;
        public ControlConfiModbus ControlModbusRTU;
        #endregion

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

            this.ParentForm = parent;

            this.InitializeDesign();
            this.DefaultSetting();
        }
        #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();

            if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.English)
            {
                this.labelTitleSelectLane.Text = "Select lane";
                this.labelTitleCommMode.Text = "Communication mode";
                this.labelTitleSetting.Text = "Setting";
                this.labelTitleSend.Text = "Send";
                this.labelTitleReceive.Text = "Receive";
                this.labelTitleAddon.Text = "Add-on";

                this.buttonTransmitCondition.DownImage = new Bitmap(images.GetImage(Class1.ButtonImages.engPassUp));
                this.buttonTransmitCondition.UpImage = new Bitmap(images.GetImage(Class1.ButtonImages.engEveryUp));

                this.smartLabel2.Text = "- U : Under range, R : Reference, O : Over range";
                this.smartLabel3.Text = "- G, Grd : Grade, W : Weight, CNT : Count, Chk : Checksum";
                this.labelTitleTransmissionDelayTime.Text = "Transmission delay time(ms)";
                //this.labelTitleCommControlCharacter.Text = "Com- control character";
                this.labelTitleCharacterToFill.Text = "Character to fill in the weight value blank";
                this.labelTitleTransmitCondition.Text = "Transmission conditions";
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Chinese)
            {
                this.labelTitleSelectLane.Text = "选择列";
                this.labelTitleCommMode.Text = "通信模式";
                this.labelTitleSetting.Text = "设定值";
                this.labelTitleSend.Text = "发送";
                this.labelTitleReceive.Text = "接受";
                this.labelTitleAddon.Text = "附加功能";

                this.buttonTransmitCondition.DownImage = new Bitmap(images.GetImage(Class1.ButtonImages.engPassUp));
                this.buttonTransmitCondition.UpImage = new Bitmap(images.GetImage(Class1.ButtonImages.engEveryUp));

                this.smartLabel2.Text = "- U : 低于, R : 通过, O : 超过";
                this.smartLabel3.Text = "- G, Grd : 等级, W : 重量, CNT : 计数, Chk : 校验和";
                this.labelTitleTransmissionDelayTime.Text = "传送延迟时间(ms)";
                //this.labelTitleCommControlCharacter.Text = "通信制御文字";
                this.labelTitleCharacterToFill.Text = "重量值填空字符";
                this.labelTitleTransmitCondition.Text = "传输条件";
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Czech)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Russian)
            {
                this.labelTitleSelectLane.Text = "Выберите столбец";
                this.labelTitleCommMode.Text = "Режим обмена";
                this.labelTitleSetting.Text = "Настройка значений";
                this.labelTitleSend.Text = "Отправить";
                this.labelTitleReceive.Text = "Получить";
                this.labelTitleAddon.Text = "Дополнения";

                this.buttonTransmitCondition.DownImage = new Bitmap(images.GetImage(Class1.ButtonImages.engPassUp));
                this.buttonTransmitCondition.UpImage = new Bitmap(images.GetImage(Class1.ButtonImages.engEveryUp));

                this.smartLabel2.Text = "- U : Мало, R : Норма, O : Много";
                this.smartLabel3.Text = "- G, Grd : Сортировка, W : Вес, CNT : Подсчет, Chk : Контрольная сумма";
                this.labelTitleTransmissionDelayTime.Text = "Время задержки передачи(ms)";
                //this.labelTitleCommControlCharacter.Text = "Коммуникационный управляющий персонаж";
                this.labelTitleCharacterToFill.Text = "Символ для заполнения поля значения веса";
                this.labelTitleTransmitCondition.Text = "Условия передачи";
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.German)
            {
                this.labelTitleSelectLane.Text = "Spalte auswählen";
                this.labelTitleCommMode.Text = "Kommunikationsmodus";
                this.labelTitleSetting.Text = "Einstellungswert";
                this.labelTitleSend.Text = "Senden";
                this.labelTitleReceive.Text = "Erhalten";
                this.labelTitleAddon.Text = "Erweiterung";

                this.buttonTransmitCondition.DownImage = new Bitmap(images.GetImage(Class1.ButtonImages.engPassUp));
                this.buttonTransmitCondition.UpImage = new Bitmap(images.GetImage(Class1.ButtonImages.engEveryUp));

                this.smartLabel2.Text = "- U : Min., R : Bestehen, O : Max.";
                this.smartLabel3.Text = "- G, Grd : Grad, W : Gewicht, CNT : Zahl, Chk : Prüfsumme";
                this.labelTitleTransmissionDelayTime.Text = "Übertragungsverzögerungszeit(ms)";
                //this.labelTitleCommControlCharacter.Text = "Kommunikationssteuerungszeichen";
                this.labelTitleCharacterToFill.Text = "Zeichen zum Ausfüllen des Leerzeichens für den Gewichtswert";
                this.labelTitleTransmitCondition.Text = "Übertragungsbedingungen";
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Spanish)
            {
                this.labelTitleSelectLane.Text = "Seleccionar columna";
                this.labelTitleCommMode.Text = "Modo de comunicación";
                this.labelTitleSetting.Text = "Setear Valor";
                this.labelTitleSend.Text = "Enviar";
                this.labelTitleReceive.Text = "Recibir";
                this.labelTitleAddon.Text = "Complementos";

                this.buttonTransmitCondition.DownImage = new Bitmap(images.GetImage(Class1.ButtonImages.engPassUp));
                this.buttonTransmitCondition.UpImage = new Bitmap(images.GetImage(Class1.ButtonImages.engEveryUp));

                this.smartLabel2.Text = "- U : Superior, R : Referencia, O : Inferior";
                this.smartLabel3.Text = "- G, Grd : Calificación, W : Peso, CNT : Conteo, Chk : Suma de comprobación";
                this.labelTitleTransmissionDelayTime.Text = "Tiempo de retardo de transmisión(ms)";
                //this.labelTitleCommControlCharacter.Text = "Carácter de control de comm";
                this.labelTitleCharacterToFill.Text = "Carácter para llenar en blanco";
                this.labelTitleTransmitCondition.Text = "Condiciones de transmisión";
            }
            else
            {
                this.labelTitleSelectLane.Text = "열 선택";
                this.labelTitleCommMode.Text = "통신 모드";
                this.labelTitleSetting.Text = "설정";
                this.labelTitleSend.Text = "송신";
                this.labelTitleReceive.Text = "수신";
                this.labelTitleAddon.Text = "추가설정";

                this.buttonTransmitCondition.DownImage = new Bitmap(images.GetImage(Class1.ButtonImages.korPassUp));
                this.buttonTransmitCondition.UpImage = new Bitmap(images.GetImage(Class1.ButtonImages.korEveryUp));

                this.smartLabel2.Text = "- U : Under range, R : Reference, O : Over range";
                this.smartLabel3.Text = "- G, Grd : Grade, W : Weight, CNT : Count, Chk : Checksum";
                this.labelTitleTransmissionDelayTime.Text = "전송 지연시간(ms)";
                //this.labelTitleCommControlCharacter.Text = "통신 제어 문자";
                this.labelTitleCharacterToFill.Text = "중량값 빈 자리 채울 문자";
                this.labelTitleTransmitCondition.Text = "전송 조건";
            }
        }
        private void DefaultSetting()
        {
            this.ControlModbusRTU = new ControlConfiModbus(this.ParentForm);
            this.Controls.Add(this.ControlModbusRTU);
            this.ControlModbusRTU.Location = new Point(0, 217);

            this.ControlVisible(false);

            this.comboBoxSerialBaudRate.Items.Clear();
            this.comboBoxSerialBaudRate.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);
            this.comboBoxSerialBaudRate.Items.Add(9600);
            this.comboBoxSerialBaudRate.Items.Add(19200);
            this.comboBoxSerialBaudRate.Items.Add(38400);
            this.comboBoxSerialBaudRate.Items.Add(57600);
            this.comboBoxSerialBaudRate.Items.Add(115200);
            this.comboBoxSerialBaudRate.SelectedIndex = 0;
            this.comboBoxSerialBaudRate.SelectedIndexChanged += new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);

            this.comboBoxSelectLane.Items.Clear();
            this.comboBoxSelectLane.SelectedIndexChanged -= new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);
            this.comboBoxSelectLane.Items.Add("All");
            this.comboBoxSelectLane.Items.Add("1");
            this.comboBoxSelectLane.Items.Add("2");
            this.comboBoxSelectLane.SelectedIndex = 0;
            this.comboBoxSelectLane.SelectedIndexChanged += new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);

            this.ChangeCommunicationMode();

            this.labelFormat.Text = "";
        }
        public void ChangeCommunicationMode()
        {
            this.comboBoxSerialMode.Items.Clear();
            this.comboBoxSerialMode.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);
            this.comboBoxSerialMode.Items.Add("None");
            this.comboBoxSerialMode.Items.Add("STD1");
            this.comboBoxSerialMode.Items.Add("Remote");
            this.comboBoxSerialMode.Items.Add("Printer");
            this.comboBoxSerialMode.Items.Add("STD2");
            this.comboBoxSerialMode.Items.Add("imaje 9028 OPT2"); // 한맥
            //this.comboBoxSerialMode.Items.Add("-");
            this.comboBoxSerialMode.SelectedIndexChanged += new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);
        }

        private void labelTitleFixTextData(string sValue)
        {
            this.labelTitleFixText.Text = sValue;
        }
        public void labelTitleFixTextVisible(bool bValue)
        {
            this.comboBoxSerialMode.Visible = !bValue;
            this.labelTitleFixText.Visible = bValue;
            if (bValue == true)
                this.comboBoxSerialBaudRate.Enabled = false;
            else
                this.comboBoxSerialBaudRate.Enabled = true;
        }

        public string ReturnBaudrateName(int num)
        {
            switch (num)
            {
                case 0:
                    return "9600";
                case 1:
                    return "19200";
                case 2:
                    return "38400";
                case 3:
                    return "57600";
                case 4:
                    return "115200";
                default:
                    return "9600";
            }
        }
        public string ReturnCommunicationModeName(int num)
        {
            if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.German)
            {
                #region 독일어
                switch (num)
                {
                    case 0:
                        return "Keiner";
                    case 1:
                        return "STD1";
                    case 2:
                        return "Fernzugriff";
                    case 3:
                        return "Drucker";
                    case 4:
                        return "STD2";
                    case 5:
                        return "imaje9028-2";
                    default:
                        return "Keiner";
                }
                #endregion
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == Define.E_LanguageID.Spanish)
            {
                #region 스페인어
                switch (num)
                {
                    case 0:
                        return "Ninguna";
                    case 1:
                        return "STD1";
                    case 2:
                        return "Remoto";
                    case 3:
                        return "Impresora industrial";
                    case 4:
                        return "STD2";
                    case 5:
                        return "imaje9028-2";
                    default:
                        return "Ninguna";
                }
                #endregion
            }
            else
            {
                #region 한국어
                switch (num)
                {
                    case 0:
                        return "None";
                    case 1:
                        return "STD1";
                    case 2:
                        return "Remote";
                    case 3:
                        return "Printer";
                    case 4:
                        return "STD2";
                    case 5:
                        return "imaje9028-2";                 
                    default:
                        return "None";
                }
                #endregion
            }
        }

        private void UpdateLabelFormatDisplay()
        {
            switch (this.comboBoxSerialMode.SelectedIndex)
            {
                case 0:  // None
                    this.labelFormat.Text = "";
                    break;
                case 1:  // STD1
                    this.labelFormat.Text = "STX[1],ID[5],No[4],U[6],P[6],O[6],Grd[1],Sign[1],Weight[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 (int)Define.E_CommMode.f4_STD2: // STD2
                    this.labelFormat.Text = "STX[1],ID[5],No[4],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;
                case (int)Define.E_CommMode.f99_Modbus:  // Modbus_TCP
                    if (this.ParentForm.ParentForm.SystemConfig.IsModbus == false)
                        this.labelFormat.Text = "-";
                    else
                        this.labelFormat.Text = "ID, Product No, Under, Pass, Over, Under Count, Pass Count, Over Count, NG Count, ExNG Count, Total Count, Grade, Weight, Status(Run/Stop)";
                    break;
                default:
                    this.buttonTestSend.Enabled = false;
                    this.labelFormat.Text = "Private use";
                    break;
            }
        }
        private void ControlVisible(bool visible)
        {
            this.ControlModbusRTU.Visible = visible;
        }
        private void ButtonAddOnDisplay()
        {
            this.ControlVisible(false);
            //this.DisplayBottomSettingMenu();

            if (this.comboBoxSerialMode.SelectedIndex == (int)Define.E_CommMode.f99_Modbus && this.ParentForm.ParentForm.SystemConfig.IsModbus == true)
                this.buttonAddon.Visible = true;
            else
                this.buttonAddon.Visible = false;
        }
        
        private void UpdateSerialParameterDisplay(SystemConfigurationItem item)
        {
            Define.E_MenuBottomConfiguration temp = this.ParentForm.CurrentConfigurationMenu();

            this.comboBoxSerialBaudRate.Enabled = true;
            this.comboBoxSerialMode.Enabled = true;
            this.labelTitleFixText.Visible = false;

            switch (temp)
            {
                case Define.E_MenuBottomConfiguration.SerialCOM1:
                    #region COM1 Load
                    this.labelTitleFixTextVisible(false);

                    this.labelTransmissionDelayTime.Text = item.TransmissionDelayTimeCOM1.ToString();
                    if (item.IsCharToFillZeroCOM1 == true)
                        this.buttonCharacterToFill.ButtonDown();
                    else
                        this.buttonCharacterToFill.ButtonUp();
                    if (item.IsTransmitWhenPassCOM1 == true)
                        this.buttonTransmitCondition.ButtonDown();
                    else
                        this.buttonTransmitCondition.ButtonUp();

                    // 열 선택
                    this.comboBoxSelectLane.SelectedIndexChanged -= new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);
                    this.comboBoxSelectLane.SelectedIndex = item.SelectLaneCOM1;
                    this.comboBoxSelectLane.SelectedIndexChanged += new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);

                    // BaudRate 
                    this.comboBoxSerialBaudRate.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);
                    this.comboBoxSerialBaudRate.SelectedIndex = item.SerialCOM1BaudRate;
                    this.comboBoxSerialBaudRate.SelectedIndexChanged += new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);

                    // Mode
                    this.comboBoxSerialMode.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);
                    this.comboBoxSerialMode.SelectedIndex = item.SerialCOM1Mode;
                    this.comboBoxSerialMode.SelectedIndexChanged += new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);
                    
                    if (this.ParentForm.ParentForm.SystemConfig.SerialCOM1Mode == (int)Define.E_CommMode.f99_Modbus
                        && this.ParentForm.ParentForm.SystemConfig.IsModbus == true)
                        this.ControlModbusRTU.ModbusRTUDefaultSettings();
                    else
                        this.ControlModbusRTU.SerialDefaultSettings();
                    #endregion
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM3:
                    #region COM3 Load
                    this.labelTransmissionDelayTime.Text = item.TransmissionDelayTimeCOM3.ToString();
                    if (item.IsCharToFillZeroCOM3 == true)
                        this.buttonCharacterToFill.ButtonDown();
                    else
                        this.buttonCharacterToFill.ButtonUp();
                    if (item.IsTransmitWhenPassCOM3 == true)
                        this.buttonTransmitCondition.ButtonDown();
                    else
                        this.buttonTransmitCondition.ButtonUp();

                    this.labelTitleFixTextVisible(false);

                    // 열 선택
                    this.comboBoxSelectLane.SelectedIndexChanged -= new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);
                    this.comboBoxSelectLane.SelectedIndex = item.SelectLaneCOM3;
                    this.comboBoxSelectLane.SelectedIndexChanged += new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);

                    // BaudRate 
                    this.comboBoxSerialBaudRate.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);
                    this.comboBoxSerialBaudRate.SelectedIndex = item.SerialCOM3BaudRate;
                    this.comboBoxSerialBaudRate.SelectedIndexChanged += new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);

                    // Mode
                    this.comboBoxSerialMode.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);
                    this.comboBoxSerialMode.SelectedIndex = item.SerialCOM3Mode;
                    this.comboBoxSerialMode.SelectedIndexChanged += new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);
                    
                    if (this.ParentForm.ParentForm.SystemConfig.SerialCOM3Mode == (int)Define.E_CommMode.f99_Modbus
                        && this.ParentForm.ParentForm.SystemConfig.IsModbus == true)
                        this.ControlModbusRTU.ModbusRTUDefaultSettings();
                    else
                        this.ControlModbusRTU.SerialDefaultSettings();
                    #endregion
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM4:
                    #region COM4 Load
                    this.labelTitleFixTextVisible(false);

                    this.labelTransmissionDelayTime.Text = item.TransmissionDelayTimeCOM4.ToString();
                    if (item.IsCharToFillZeroCOM4 == true)
                        this.buttonCharacterToFill.ButtonDown();
                    else
                        this.buttonCharacterToFill.ButtonUp();
                    if (item.IsTransmitWhenPassCOM4 == true)
                        this.buttonTransmitCondition.ButtonDown();
                    else
                        this.buttonTransmitCondition.ButtonUp();

                    // 열 선택
                    this.comboBoxSelectLane.SelectedIndexChanged -= new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);
                    this.comboBoxSelectLane.SelectedIndex = item.SelectLaneCOM4;
                    this.comboBoxSelectLane.SelectedIndexChanged += new EventHandler(this.comboBoxSelectLane_SelectedIndexChanged);

                    // BaudRate 
                    this.comboBoxSerialBaudRate.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);
                    this.comboBoxSerialBaudRate.SelectedIndex = item.SerialCOM4BaudRate;
                    this.comboBoxSerialBaudRate.SelectedIndexChanged += new EventHandler(this.comboBoxSerialBaudRate_SelectedIndexChanged);

                    // Mode
                    this.comboBoxSerialMode.SelectedIndexChanged -= new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);
                    this.comboBoxSerialMode.SelectedIndex = item.SerialCOM4Mode;
                    this.comboBoxSerialMode.SelectedIndexChanged += new EventHandler(this.comboBoxSerialMode_SelectedIndexChanged);


                    if (this.ParentForm.ParentForm.SystemConfig.SerialCOM4Mode == (int)Define.E_CommMode.f99_Modbus
                        && this.ParentForm.ParentForm.SystemConfig.IsModbus == true)
                        this.ControlModbusRTU.ModbusRTUDefaultSettings();
                    else
                        this.ControlModbusRTU.SerialDefaultSettings();
                    #endregion
                    break;
                default:
                    break;
            }

            if (this.comboBoxSerialMode.SelectedIndex != 0)
                this.buttonTestSend.Enabled = true;

            this.DisplayReceive("");
            this.ButtonAddOnDisplay();
            this.UpdateLabelFormatDisplay();
        }
        private void SaveComboBox(int baudrate, int mode)
        {
            string[] beforeBaudrate = new string[3];
            string[] afterBaudrate = new string[3];
            string[] beforeMode = new string[3];
            string[] afterMode = new string[3];

            Define.E_MenuBottomConfiguration temp = this.ParentForm.CurrentConfigurationMenu();

            //beforeBaudrate[0] = this.ReturnBaudrateName(this.ParentForm.ParentForm.SystemConfig.SerialCOM1BaudRate);
            //beforeBaudrate[1] = this.ReturnBaudrateName(this.ParentForm.ParentForm.SystemConfig.SerialCOM3BaudRate);
            //beforeBaudrate[2] = this.ReturnBaudrateName(this.ParentForm.ParentForm.SystemConfig.SerialCOM4BaudRate);
            //beforeMode[0] = this.ReturnCommunicationModeName(this.ParentForm.ParentForm.SystemConfig.SerialCOM1Mode);
            //beforeMode[1] = this.ReturnCommunicationModeName(this.ParentForm.ParentForm.SystemConfig.SerialCOM3Mode);
            //beforeMode[2] = this.ReturnCommunicationModeName(this.ParentForm.ParentForm.SystemConfig.SerialCOM4Mode);

            this.ControlModbusRTU.SerialDefaultSettings();

            switch (temp)
            {
                case Define.E_MenuBottomConfiguration.SerialCOM1:
                    this.ParentForm.ParentForm.CloseSerialCOM1();

                    this.ParentForm.ParentForm.SystemConfig.SerialCOM1BaudRate = baudrate;
                    this.ParentForm.ParentForm.SystemConfig.SerialCOM1Mode = mode;

                    if (mode == (int)Define.E_CommMode.f3_Printer)
                    {
                        this.ParentForm.CenterBasicDataStatistics.DisplayPrintButton(this.ParentForm.ParentForm.SystemConfig);
                        this.ParentForm.ParentForm.ChildFormMainDisplay.DisplayPrintButton(this.ParentForm.ParentForm.SystemConfig);
                    }

                    this.ParentForm.ParentForm.ChangeSerialCOM1FrameSeparateType(Define.E_SeparateType.NONEFRAME_READTIMEOUT);
                    this.ParentForm.ParentForm.OpenSerialCOM1();
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM3:
                    this.ParentForm.ParentForm.CloseSerialCOM3();

                    this.ParentForm.ParentForm.SystemConfig.SerialCOM3BaudRate = baudrate;
                    this.ParentForm.ParentForm.SystemConfig.SerialCOM3Mode = mode;

                    if (mode == (int)Define.E_CommMode.f3_Printer)
                    {
                        this.ParentForm.CenterBasicDataStatistics.DisplayPrintButton(this.ParentForm.ParentForm.SystemConfig);
                        this.ParentForm.ParentForm.ChildFormMainDisplay.DisplayPrintButton(this.ParentForm.ParentForm.SystemConfig);
                    }

                    this.ParentForm.ParentForm.ChangeSerialCOM3FrameSeparateType(Define.E_SeparateType.NONEFRAME_READTIMEOUT);
                    this.ParentForm.ParentForm.OpenSerialCOM3();
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM4:
                    this.ParentForm.ParentForm.CloseSerialCOM4();

                    this.ParentForm.ParentForm.SystemConfig.SerialCOM4BaudRate = baudrate;
                    this.ParentForm.ParentForm.SystemConfig.SerialCOM4Mode = mode;

                    this.ParentForm.ParentForm.ChangeSerialCOM4FrameSeparateType(Define.E_SeparateType.NONEFRAME_READTIMEOUT);
                    this.ParentForm.ParentForm.OpenSerialCOM4();
                    break;
                default:
                    break;
            }

            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);
                this.ParentForm.ParentForm.SystemConfig.ModbusRTUSelectFunction = (int)Define.E_ModbusFunction._04_ReadInputRegister;
            }
            else
                this.ParentForm.ParentForm.ChildFormMainDisplay.MainBottomModbusIconAdd(false);
            
            //afterBaudrate[0] = this.ReturnBaudrateName(this.ParentForm.ParentForm.SystemConfig.SerialCOM1BaudRate);
            //afterBaudrate[1] = this.ReturnBaudrateName(this.ParentForm.ParentForm.SystemConfig.SerialCOM3BaudRate);
            //afterBaudrate[2] = this.ReturnBaudrateName(this.ParentForm.ParentForm.SystemConfig.SerialCOM4BaudRate);
            //afterMode[0] = this.ReturnCommunicationModeName(this.ParentForm.ParentForm.SystemConfig.SerialCOM1Mode);
            //afterMode[1] = this.ReturnCommunicationModeName(this.ParentForm.ParentForm.SystemConfig.SerialCOM3Mode);
            //afterMode[2] = this.ReturnCommunicationModeName(this.ParentForm.ParentForm.SystemConfig.SerialCOM4Mode);

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

        public void ModbusSetting()
        {

        }

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

            this.buttonSave.Enabled = false;
            this.UpdateSerialParameterDisplay(this.ParentForm.ParentForm.SystemConfig);
        }

        public void DisplayReceive(string value)
        {
            this.labelReceive.Text = value;
        }
        private void DisplayBottomSettingMenu()
        {
            this.ControlVisible(false);

            this.buttonTestSend.Enabled = true;

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

            }
        }
        #endregion

        #region Event Handler
        private void buttonAddon_Click(object sender, EventArgs e)
        {
            if (this.ControlModbusRTU.Visible == false)
                this.DisplayBottomSettingMenu();
            else
            {
                this.ControlVisible(false);
            }
        }

        private void buttonTestSend_Click(object sender, EventArgs e)
        {
            int tempStringLength = 0;
            string tempString = "";
            string str = "";
            bool isTest = true;
            bool isFillZero = false;

            StringBuilder sb = new StringBuilder();
            Define.E_MenuBottomConfiguration temp = this.ParentForm.CurrentConfigurationMenu();
            switch (temp)
            {
                case Define.E_MenuBottomConfiguration.SerialCOM1:
                    isFillZero = this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM1;
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM3:
                    isFillZero = this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM3;
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM4:
                    isFillZero = this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM4;
                    break;
                default:
                    break;
            }
            byte[] byteArray = new byte[11];
            byte[] weightBytes = new byte[5];
            byte[] bytes = new byte[100];

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

            switch (this.comboBoxSerialMode.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(" ");
                    if (isFillZero == true)
                        sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("1234", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    else
                        sb.Append(this.ParentForm.ParentForm.PadLeft(6, Helper.StringToDecimalPlaces("1234", 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");
                    if (isFillZero == true)
                        sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("1234", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    else
                        sb.Append(this.ParentForm.ParentForm.PadLeft(6, 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");
                    #endregion
                    break;
                case (int)Define.E_CommMode.f4_STD2:
                    #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(" ");
                    if (isFillZero == true)
                        sb.Append(Helper.StringZeroFillDigits6(Helper.StringToDecimalPlaces("1234", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    else
                        sb.Append(this.ParentForm.ParentForm.PadLeft(6, Helper.StringToDecimalPlaces("1234", this.ParentForm.ParentForm.SystemConfig.DecimalPlaces)));
                    sb.Append((char)0x03);
                    #endregion
                    break;
                case (int)Define.E_CommMode.f5_imaje_9028_OPT2:
                    #region imaje 9028 OPT2
                    // 중량발송 : 0x99
                    byteArray[0] = 0x99;

                    // Length : 0x00, 0x02 고정값
                    byteArray[1] = 0x00;
                    byteArray[2] = 0x07;
                    byteArray[3] = 0x12;
                    weightBytes = new UTF8Encoding().GetBytes("123.4");
                    for (int i = 0; i < weightBytes.Length; i++)
                    {
                        byteArray[i + 4] = weightBytes[i];
                    }
                    byteArray[9] = 0x12;
                    byteArray[10] = 0x00;
                    byteArray[10] = Helper.ChecksumCalculator(byteArray);
                    #endregion
                    break;
                default:
                    isTest = false;
                    break;
            }

            switch (temp)
            {
                case Define.E_MenuBottomConfiguration.SerialCOM1:
                    if (isTest == true && this.ParentForm.ParentForm.CheckOpenCOM1() == true)
                    {
                        if (sb.ToString() == "")
                            this.ParentForm.ParentForm.TransferDirectSerialCOM1(byteArray);
                        else
                            this.ParentForm.ParentForm.TransferDirectSerialCOM1(sb.ToString());
                    }
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM3:
                    if (isTest == true && this.ParentForm.ParentForm.CheckOpenCOM3() == true)
                    {
                        if (sb.ToString() == "")
                            this.ParentForm.ParentForm.TransferDirectSerialCOM3(byteArray);
                        else
                            this.ParentForm.ParentForm.TransferDirectSerialCOM3(sb.ToString());
                    }
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM4:
                    if (isTest == true && this.ParentForm.ParentForm.CheckOpenCOM4() == true)
                    {
                        if (sb.ToString() == "")
                            this.ParentForm.ParentForm.TransferDirectSerialCOM4(byteArray);
                        else
                            this.ParentForm.ParentForm.TransferDirectSerialCOM4(sb.ToString());
                    }
                    break;
                default:
                    break;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (this.comboBoxSerialMode.SelectedIndex != 0)
                this.buttonTestSend.Enabled = true;

            this.SaveComboBox(this.comboBoxSerialBaudRate.SelectedIndex, this.comboBoxSerialMode.SelectedIndex);
            this.ParentForm.ParentForm.ChildFormMainDisplay.UpdateIcomDisplay();

            //this.ButtonAddOnDisplay();
            this.buttonSave.Enabled = false;
        }

        private void comboBoxSerialBaudRate_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.buttonSave.Enabled = true;
        }
        private void comboBoxSerialMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.comboBoxSerialBaudRate.Enabled = true;
            this.buttonSave.Enabled = true;

            this.UpdateLabelFormatDisplay();
        }

        private void labelTransmissionDelayTime_Click(object sender, EventArgs e)
        {
            string value = "";
            DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelTransmissionDelayTime.Text, 4, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

            if (myKeyPad.ShowDialog() == DialogResult.OK)
            {
                if (myKeyPad.doubleValue < 0 || myKeyPad.doubleValue > 9999)
                {
                    // 입력범위를 확인하세요
                    DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                    myMsg.ShowDialog();
                }
                else
                {
                    this.labelTransmissionDelayTime.Text = myKeyPad.StringValue;

                    value = Helper.StringZeroFillDigits4(this.labelTransmissionDelayTime.Text);

                    Define.E_MenuBottomConfiguration temp = this.ParentForm.CurrentConfigurationMenu();
                    if (temp == Define.E_MenuBottomConfiguration.SerialCOM1)
                        this.ParentForm.ParentForm.SystemConfig.TransmissionDelayTimeCOM1 = myKeyPad.IntValue;
                    else if (temp == Define.E_MenuBottomConfiguration.SerialCOM3)
                        this.ParentForm.ParentForm.SystemConfig.TransmissionDelayTimeCOM3 = myKeyPad.IntValue;
                    else if (temp == Define.E_MenuBottomConfiguration.SerialCOM4)
                        this.ParentForm.ParentForm.SystemConfig.TransmissionDelayTimeCOM4 = myKeyPad.IntValue;

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

        private void buttonCharacterToFill_Click(object sender, EventArgs e)
        {
            Define.E_MenuBottomConfiguration temp = this.ParentForm.CurrentConfigurationMenu();

            if (this.buttonCharacterToFill.ButtonStatus == SmartX.SmartButton.BUTSTATUS.DOWN)
            {
                switch (temp)
                {
                    case Define.E_MenuBottomConfiguration.SerialCOM1:
                        this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM1 = true;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM3:
                        this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM3 = true;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM4:
                        this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM4 = true;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch (temp)
                {
                    case Define.E_MenuBottomConfiguration.SerialCOM1:
                        this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM1 = false;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM3:
                        this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM3 = false;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM4:
                        this.ParentForm.ParentForm.SystemConfig.IsCharToFillZeroCOM4 = false;
                        break;
                    default:
                        break;
                }
            }
            this.ParentForm.ParentForm.SaveSystemConfigurationFile2(this.ParentForm.ParentForm.SystemConfig);
        }
        private void buttonTransmitCondition_Click(object sender, EventArgs e)
        {
            Define.E_MenuBottomConfiguration temp = this.ParentForm.CurrentConfigurationMenu();

            if (this.buttonTransmitCondition.ButtonStatus == SmartX.SmartButton.BUTSTATUS.DOWN)
            {
                switch (temp)
                {
                    case Define.E_MenuBottomConfiguration.SerialCOM1:
                        this.ParentForm.ParentForm.SystemConfig.IsTransmitWhenPassCOM1 = true;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM3:
                        this.ParentForm.ParentForm.SystemConfig.IsTransmitWhenPassCOM3 = true;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM4:
                        this.ParentForm.ParentForm.SystemConfig.IsTransmitWhenPassCOM4 = true;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch (temp)
                {
                    case Define.E_MenuBottomConfiguration.SerialCOM1:
                        this.ParentForm.ParentForm.SystemConfig.IsTransmitWhenPassCOM1 = false;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM3:
                        this.ParentForm.ParentForm.SystemConfig.IsTransmitWhenPassCOM3 = false;
                        break;
                    case Define.E_MenuBottomConfiguration.SerialCOM4:
                        this.ParentForm.ParentForm.SystemConfig.IsTransmitWhenPassCOM4 = false;
                        break;
                    default:
                        break;
                }
            }
            this.ParentForm.ParentForm.SaveSystemConfigurationFile2(this.ParentForm.ParentForm.SystemConfig);
        }

        private void comboBoxCommControlCharacter_SelectedIndexChanged(object sender, EventArgs e)
        {
            //this.ParentForm.ParentForm.SystemConfig.CommunicationControlCharacter = this.comboBoxCommControlCharacter.SelectedIndex;
            this.ParentForm.ParentForm.SaveSystemConfigurationFile2(this.ParentForm.ParentForm.SystemConfig);
        }
        private void comboBoxSelectLane_SelectedIndexChanged(object sender, EventArgs e)
        {
            Define.E_MenuBottomConfiguration temp = this.ParentForm.CurrentConfigurationMenu();

            switch (temp)
            {
                case Define.E_MenuBottomConfiguration.SerialCOM1:
                    this.ParentForm.ParentForm.SystemConfig.SelectLaneCOM1 = this.comboBoxSelectLane.SelectedIndex;
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM3:
                    this.ParentForm.ParentForm.SystemConfig.SelectLaneCOM3 = this.comboBoxSelectLane.SelectedIndex;
                    break;
                case Define.E_MenuBottomConfiguration.SerialCOM4:
                    this.ParentForm.ParentForm.SystemConfig.SelectLaneCOM4 = this.comboBoxSelectLane.SelectedIndex;
                    break;
                default:
                    break;
            }

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