using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections.Concurrent;
using System.Threading;
using System.Timers;
using System.Net.NetworkInformation;

namespace BEMSDataGateway
{
    public partial class Form1 : Form
    {
        IcosComm iCosSocket;                     //iCos 통신클래스
        LogFileCreate LFC = new LogFileCreate(); //로그 기록 파일
        My_TimerThread MTT = new My_TimerThread();
        System.Timers.Timer timer_NetStat = new System.Timers.Timer();
        public static bool Enable_EnglishMode;
        Parsing PS = new Parsing();
        string szICOS_IP;         //iCos server 주소
        string szICOS_ID;         //iCos server ID
        string szICOS_PW;         //iCos server Password
        string szDB_IP;           //iCos 프로젝트 DB 주소
        string szDB_NAME;         //iCos 프로젝트 DB 이름
        string szDB_ID;           //iCos 프로젝트 DB 접속 ID
        string szDB_PW;           //iCos 프로젝트 DB 접속 비밀번호
        int nDB_TYPE = 1;         //iCos 프로젝트 DB 종류 (0:MDB, 1:MS-SQL)
        public bool bConnect;

        public void CommResponse(string userid, int nType, int nSubType, Object obj) //iCOS 응답처리를 위한 함수
        {
            if (nType == 6)
            {
                if (nSubType == 2)
                {
                    iCosLogInResponse _packet = (iCosLogInResponse)obj;
                    string errMsg;

                    if (_packet.nResult == 3) //로그인 성공
                    {
                        if (Enable_EnglishMode)//영어
                        {
                            LFC.Log("Successfully logged in to the iCOS 4 server" + Environment.NewLine);
                        }
                        else//한글
                        {
                            LFC.Log("iCOS 4 서버에 로그인 성공" + Environment.NewLine);
                        }
                        Wirte_state_PointSetBtn(PointSetBtn);
                        Wirte_PointSetBtn(PointSetBtn);
                    }
                    else //로그인 실패
                    {
                        if (_packet.nResult == 0)
                            errMsg = "DB Error";
                        else if (_packet.nResult == 1)
                            errMsg = "Password Error";
                        else if (_packet.nResult == 2)
                            errMsg = "ID Error";
                        else
                            errMsg = "Other Errors";
                        if (Enable_EnglishMode)//영어
                        {
                            LFC.Log("[Form] iCOS4 server Login failure : " + errMsg + Environment.NewLine);
                            Wirte_logtxt(Convert.ToString(DateTime.Now) + "[Form] iCOS4 server Login failure : " + errMsg + Environment.NewLine);
                        }
                        else//한글
                        {
                            LFC.Log("[Form] iCOS4 로그인 실패 : " + errMsg + Environment.NewLine);
                            Wirte_logtxt(Convert.ToString(DateTime.Now) + "[Form] iCOS4 로그인 실패 : " + errMsg + Environment.NewLine);
                        }
                        //Wirte_ProStopBtn(ProStopBtn);
                        LFC.Log("[Form] iCOS4 서버 연결실패 : 3분후 재 로그인을 진행합니다." + Environment.NewLine);
                        Wirte_logtxt(Convert.ToString(DateTime.Now) + "[Form] iCOS4 로그인 실패 : 3분후 재 로그인을 진행합니다" + Environment.NewLine);
                        Delay(180000);
                        iCosSocket.IcosLogin(szICOS_ID, szICOS_PW);
                    }
                }
            }
            else if (nType == 4) //알람
            {
                if (nSubType == 11)
                {
                    //알람이 발생하면 여기로 들어온다.
                }
                else if (nSubType == 9) //ALARM_ACK_FROM_SERVER
                {
                    //서버로 부터 알람에 대한 인지가 발생하면 여기로 들어온다.
                }
                else if (nSubType == 16) //ALARM_CHACK_ALL_PROCESS_FROM_SERVER
                {
                    //서버로 부터 모든 알람에 대한 인지가 발생하면 여기로 들어온다.
                }
                else
                {
                    // 그외에 알람관련 정보를 받으면 여기로 들어온다.
                }
            }
            else if (nType == 99)
            {
                //iCos 서버와의 접속이 끊기고 연결오류 발생시 여기로 들어온다.
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form]The socket connection was broken by the iCos4 server" + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form]iCos4 서버에 의해서 소켓 연결이 끊어졌습니다" + Environment.NewLine);
                }
            }
        }
        public static DateTime Delay(int MS)
        {

            DateTime ThisMoment = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
            DateTime AfterWards = ThisMoment.Add(duration);

            while (AfterWards >= ThisMoment)
            {
                System.Windows.Forms.Application.DoEvents();
                ThisMoment = DateTime.Now;
            }
            return DateTime.Now;
        }

        public bool iCos4ConnectandLogin(string address, string id, string password)// iCOS4 네트워크 상태 파악 함수, 0 : 연결 안됨, 1: 정상 상태
        {
            bool bRet = false;
            var state = iCosSocket.GetConnectionStatus(id);

            if (state)
            {
                iCosSocket.reDisconnect(id);
            }
            if (iCosSocket.Connect(address, 6000, id, password)) //iCOS 소켓 연결
            {
                iCosSocket.IcosLogin(id, password); //iCOS 로그인
                bRet = true;
            }
            else
            {
                iCosSocket.Disconnect(id); //iCOS 소켓 연결 해제
            }
            return bRet;
        }

        public string iCos4Connect() //iCOS 연결 함수
        {
            string strRet = "";
            string Result_Connect_iCos = "";
            Readini Ri = new Readini();
            Ri.ReadData(); // ini의 설정값을 불러옴.
            szICOS_IP = Ri.IP1;
            szICOS_ID = Ri.ICOS_ID;
            szICOS_PW = Ri.ICOS_PASSWORD;
            nDB_TYPE = Convert.ToInt32(Ri.ICOSDB_TYPE);
            szDB_IP = Ri.ICOSDB_LOC;
            szDB_NAME = Ri.ICOSDB_NAME;
            szDB_ID = Ri.ICOSDB_ID;
            szDB_PW = Ri.ICOSDB_PASSWORD;
            Enable_EnglishMode = Ri.Enable_EnglishMode;

            this.ProSetBtn.Text = (Enable_EnglishMode ? "Connection setup" : "접속 설정");
            this.ProPathBtn.Text = (Enable_EnglishMode ? "Open project folder" : "프로젝트 폴더 열기");
            this.Conn_iCos_Btn.Text = (Enable_EnglishMode ? "iCos \r\nconnect" : "iCos \r\n접속");
            this.PointSetBtn.Text = (Enable_EnglishMode ? "Registration of control point" : "관제점 등록");
            this.PointUnRegBtn.Text = (Enable_EnglishMode ? "Disable control point" : "관제점 해제");
            this.ProStartBtn.Text = (Enable_EnglishMode ? "Start" : "시작");
            this.ProStopBtn.Text = (Enable_EnglishMode ? "Stop" : "중단");
            this.EraseLog.Text = (Enable_EnglishMode ? "Log\r\nClear" : "로그\r\n지우기");
            this.groupBox1.Text = (Enable_EnglishMode ? "Preferences" : "환경설정");
            this.groupBox5.Text = (Enable_EnglishMode ? "Monitoring" : "모니터링");
            this.label6.Text = (Enable_EnglishMode ? "Start \r\nTime" : "시작시간");
            this.label4.Text = (Enable_EnglishMode ? "End \r\nTime" : "종료시간");
            this.label10.Text = (Enable_EnglishMode ? "Communication status" : "통신상태");
            this.label11.Text = (Enable_EnglishMode ? "Verify the value" : "값 확인");
            this.AllValueCheck_btn.Text = (Enable_EnglishMode ? "Batch verification of values" : "값 일괄 확인");
            this.RequestValue_btn.Text = (Enable_EnglishMode ? "Identify specific values" : "특정 값 확인");
            this.groupBox4.Text = (Enable_EnglishMode ? "Log message" : "로그 메시지");

            try
            {
                if (!iCosSocket.InitTagAddress(nDB_TYPE, szDB_IP, szDB_NAME, szDB_ID, szDB_PW)) // iCOS DB 정보 가져옴
                {
                    if (!iCosSocket.InitTagAddress(nDB_TYPE, szDB_IP, szDB_NAME, szDB_ID, szDB_PW)) //1차 실패시, iCOS DB 정보 다시 가져옴
                    {

                        if (Enable_EnglishMode)//영어
                        {
                            Result_Connect_iCos = "Final failure of iCOS control point DB information setting";
                        }
                        else//한글
                        {
                            Result_Connect_iCos = "iCOS 관제점 DB정보 설정 최종실패";
                        }
                        return Result_Connect_iCos;
                    }
                }
                iCosSocket.InitThread(); // iCoS 연결관리
                bool bRet = iCos4ConnectandLogin(szICOS_IP, szICOS_ID, szICOS_PW);
                if (bRet == false)
                {
                    Result_Connect_iCos = "FAIL";
                }
                else
                {
                    strRet = bRet.ToString();
                    Result_Connect_iCos = "SUCCESS";
                }
            }
            catch (Exception)
            {
                Result_Connect_iCos = "FAIL";
            }
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
            return Result_Connect_iCos;
        }

        string[] ReturnTag = new string[2];

        public void ReadTag() //iCOS 태그 등록 함수
        {
            int i;
            Parsing Ps = new Parsing();
            Control_Point_Group CPG = new Control_Point_Group();
            ReturnTag = Ps.TagParsing();

            i = iCosSocket.IcosRegTag(szICOS_ID, Convert.ToInt32(ReturnTag[1]), ReturnTag[0]);//Tag 등록
            if (i == 1)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Completion of control point registration " + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Completion of control point registration" + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("관제점 등록 완료 " + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 관제점 등록 완료" + Environment.NewLine);
                }
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Point entry failed" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Point entry failed" + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] 관제점 등록 실패" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 관제점 등록 실패" + Environment.NewLine);
                }
                return;
            }
            PS.setIcosSocket(iCosSocket);
            CPG.setIcosSocket(iCosSocket);
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
        }
        System.Timers.Timer timer2 = new System.Timers.Timer();

        public int UnReg()//iCOS 태그 해제 함수
        {
            int i;
            ReturnTag = PS.TagParsing();
            Control_Point_Group CPG = new Control_Point_Group();
            i = iCosSocket.IcosUnregTag(szICOS_ID, Convert.ToInt32(ReturnTag[1]), ReturnTag[0]);//태그 등록 해제
            PS.setIcosSocket(iCosSocket);
            CPG.setIcosSocket(iCosSocket);
            if (i == 1)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Completion of control point" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Completion of control point" + Environment.NewLine);
                    LogTxt.Select(LogTxt.Text.Length, 0);
                    LogTxt.ScrollToCaret();
                }
                else//한글
                {
                    LFC.Log("[Form] 관제점 해제 완료" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 관제점 해제 완료" + Environment.NewLine);
                    LogTxt.Select(LogTxt.Text.Length, 0);
                    LogTxt.ScrollToCaret();
                }
                return 1;
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Failure to control point" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Failure to control point" + Environment.NewLine);
                    LogTxt.Select(LogTxt.Text.Length, 0);
                    LogTxt.ScrollToCaret();
                }
                else//한글
                {
                    LFC.Log("[Form] 관제점 해제 실패" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 관제점 해제 실패" + Environment.NewLine);
                    LogTxt.Select(LogTxt.Text.Length, 0);
                    LogTxt.ScrollToCaret();
                }
                return 0;
            }
        }
        public static bool Ping_SyncCheck(string DestIP)
        {
            try
            {
                if (DestIP == null || DestIP.Trim().Length == 0) return false;

                Ping pingSender = new Ping();
                PingOptions options = new PingOptions();
                options.DontFragment = true;
                string data = "0123456789";
                byte[] buffer = Encoding.ASCII.GetBytes(data);

                PingReply reply = pingSender.Send(DestIP, 1000, buffer, options);

                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public Form1() //Form 함수
        {
            InitializeComponent(); //Form 초기화
            iCosSocket = new IcosComm();
            // iCos 통신클래스와 연동을 위한 딜리게이트 함수설정
            iCosSocket.iCosResponse += new IcosComm.iCosCallback(CommResponse);
            Timer_netStat(); //iCOS 네트워크 연결 확인 함수
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            ProStopBtn.Enabled = false;
            PointSetBtn.Enabled = false;
            PointUnRegBtn.Enabled = false;
            ProStartBtn.Enabled = false;
            ProStopBtn.Enabled = false;
            AllValueCheck_btn.Enabled = false;
            RequestValue_btn.Enabled = false;
            Shown += Form_Shown;
        }

        public void Timer_netStat() //iCOS 연결 상태 확인 쓰레드 동작 함수
        {
            timer_NetStat.Interval = 10 * 1000;
            timer_NetStat.Elapsed += new ElapsedEventHandler(net_state_Thread);
            timer_NetStat.Start();
        }
        string prevconnectstate = "";
        string prevpingstate = "";
        public void net_state_Thread(object sender, ElapsedEventArgs e) //iCOS 연결 상태 확인 쓰레드 함수
        {
            int nNet;
            string strRet;
            string connectstate = "";

            try
            {
                if (Ping_SyncCheck(szICOS_IP) == true) // Ping 성공
                {
                    nNet = Convert.ToInt32(iCosSocket.GetConnectionStatus(szICOS_ID));
                    strRet = nNet.ToString();

                    if (strRet == "1")
                    {
                        if (prevconnectstate == "ICOS Communication") // O->O 
                        {
                            connectstate = "ICOS Communication";
                        }
                        else if (prevconnectstate == "ICOS Communication lost") //X -> O / ping onoff시 
                        {
                            if (prevpingstate == "pingerror")
                            {
                                Wirte_state_Conn_iCos_Btn(Conn_iCos_Btn);
                                Wirte_Conn_iCos_Btn(Conn_iCos_Btn);
                                prevpingstate = "";
                            }
                            else
                            {
                                if (Enable_EnglishMode)//영어
                                {
                                    Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS Communication" + Environment.NewLine);
                                }
                                else//한글
                                {
                                    Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS 연결" + Environment.NewLine);
                                }
                            }
                            connectstate = "ICOS Communication";
                            Wirte_Net_Stat(connectstate);
                        }
                        else //시작
                        {
                            connectstate = "ICOS Communication";
                            Wirte_Net_Stat(connectstate);
                        }
                    }
                    else
                    {
                        if (prevconnectstate == "ICOS Communication") // O->X
                        {
                            Wirte_state_ProStartBtn(ProStartBtn);
                            Wirte_state_PointSetBtn(PointSetBtn);
                            Wirte_state_Conn_iCos_Btn(Conn_iCos_Btn);
                            connectstate = "ICOS Communication lost";
                            Wirte_Net_Stat(connectstate);
                            if (Enable_EnglishMode)//영어
                            {
                                Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS Communication lost" + Environment.NewLine);
                            }
                            else//한글
                            {
                                Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS 연결 실패" + Environment.NewLine);
                            }
                        }
                        else if (prevconnectstate == "ICOS Communication lost") //X->X
                        {
                            connectstate = "ICOS Communication lost";
                        }
                        else //시작
                        {
                            connectstate = "ICOS Communication lost";
                            Wirte_Net_Stat(connectstate);

                            if (Enable_EnglishMode)//영어
                            {
                                Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS Communication lost" + Environment.NewLine);
                            }
                            else//한글
                            {
                                Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS 연결 실패" + Environment.NewLine);
                            }
                        }
                    }
                    prevconnectstate = connectstate;
                }
                else // Ping 실패
                {
                    if (Enable_EnglishMode)//영어
                    {
                        LFC.Log("[Form] ICOS Communication lost(Ping) Error" + Environment.NewLine);
                        Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS Communication lost(Ping) Error" + Environment.NewLine);
                    }
                    else//한글
                    {
                        LFC.Log("[Form] ICOS 연결 실패(Ping) 오류" + Environment.NewLine);
                        Wirte_logtxt(Convert.ToString(DateTime.Now) + " ICOS 연결 실패(Ping) 오류" + Environment.NewLine);
                    }

                    connectstate = "ICOS Communication lost";
                    prevconnectstate = connectstate;
                    Wirte_Net_Stat(connectstate);
                    prevpingstate = "pingerror";
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] net_state_Thread Error : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] net_state_Thread Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] net_state_Thread 오류 : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] net_state_Thread 오류 : " + E + Environment.NewLine);
                }
            }
        }

        private delegate void myDelegate_button(Button btn);
        private void Wirte_PointSetBtn(Button btn)  ////관제점 재 등록
        {
            try
            {
                if (this.PointSetBtn.InvokeRequired)
                {
                    myDelegate_button d = new myDelegate_button(Wirte_PointSetBtn);
                    this.Invoke(d, btn);
                }
                else
                {
                    this.PointSetBtn.PerformClick();
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Wirte_PointSetBtn Error : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_PointSetBtn Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] Wirte_PointSetBtn 오류 : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_PointSetBtn 오류 : " + E + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }
        private void Wirte_Conn_iCos_Btn(Button btn)  ////관제점 재 등록
        {
            try
            {
                if (this.Conn_iCos_Btn.InvokeRequired)
                {
                    myDelegate_button d = new myDelegate_button(Wirte_Conn_iCos_Btn);
                    this.Invoke(d, btn);
                }
                else
                {
                    this.Conn_iCos_Btn.PerformClick();
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Wirte_Conn_iCos_Btn Error : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_Conn_iCos_Btn Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] Wirte_Conn_iCos_Btn 오류 : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_Conn_iCos_Btn 오류 : " + E + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }
        private void Wirte_state_ProStartBtn(Button btn)  //시작버튼 초기화
        {
            try
            {
                if (this.ProStartBtn.InvokeRequired)
                {
                    myDelegate_button d = new myDelegate_button(Wirte_state_ProStartBtn);
                    this.Invoke(d, btn);
                }
                else
                {
                    this.ProStartBtn.Enabled = true;
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Wirte_state_ProStartBtn Error : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_state_ProStartBtn Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] Wirte_state_ProStartBtn 오류 : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_state_ProStartBtn 오류 : " + E + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }
        private void Wirte_state_PointSetBtn(Button btn)  //관제점 버튼 초기화
        {
            try
            {
                if (this.PointSetBtn.InvokeRequired)
                {
                    myDelegate_button d = new myDelegate_button(Wirte_state_PointSetBtn);
                    this.Invoke(d, btn);
                }
                else
                {
                    this.PointSetBtn.Enabled = true;
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Wirte_state_PointSetBtn Error : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_state_PointSetBtn Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] Wirte_state_PointSetBtn 오류 : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_state_PointSetBtn 오류 : " + E + Environment.NewLine);
                }

                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }
        private void Wirte_state_Conn_iCos_Btn(Button btn)  //ICOS 연결 버튼 초기화
        {
            try
            {
                if (this.Conn_iCos_Btn.InvokeRequired)
                {
                    myDelegate_button d = new myDelegate_button(Wirte_state_Conn_iCos_Btn);
                    this.Invoke(d, btn);
                }
                else
                {
                    this.Conn_iCos_Btn.Enabled = true;
                }
            }
            catch (Exception E)
            {
                LFC.Log("[Form] Wirte_state_Conn_iCos_Btn 오류 : " + E + Environment.NewLine);
                LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_state_Conn_iCos_Btn 오류 : " + E + Environment.NewLine);
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }

        private void Wirte_ProStopBtn(Button btn)  //ICOS 연결 버튼 초기화
        {
            try
            {
                if (this.ProStopBtn.InvokeRequired)
                {
                    myDelegate_button d = new myDelegate_button(Wirte_ProStopBtn);
                    this.Invoke(d, btn);
                }
                else
                {
                    this.ProStopBtn.PerformClick();
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Wirte_ProStopBtn Error : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_ProStopBtn Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] Wirte_ProStopBtn 오류 : " + E + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " [Form] Wirte_ProStopBtn 오류 : " + E + Environment.NewLine);
                }

                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }

        private delegate void myDelegate_error(string theValue);
        private void Wirte_logtxt(string theValue)  //통신상태 변화 Form text box에 적용 함수
        {
            try
            {
                if (this.LogTxt.InvokeRequired)
                {
                    myDelegate_error d = new myDelegate_error(Wirte_logtxt);
                    this.Invoke(d, new object[] { theValue });
                }
                else
                {
                    this.LogTxt.AppendText(theValue);
                    LogTxt.Select(LogTxt.Text.Length, 0);
                    LogTxt.ScrollToCaret();
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Wirte_logtxt Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] Wirte_logtxt 오류 : " + E + Environment.NewLine);
                }
            }
        }

        private delegate void myDelegate_state(string theValue);
        private void Wirte_Net_Stat(string theValue)  //통신상태 변화 Form text box에 적용 함수
        {
            try
            {
                if (this.Net_Stat.InvokeRequired)
                {
                    myDelegate_state d = new myDelegate_state(Wirte_Net_Stat);
                    this.Invoke(d, new object[] { theValue });
                }
                else
                {
                    this.Net_Stat.Text = theValue;
                }
            }
            catch (Exception E)
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("[Form] Wirte_Net_Stat Error : " + E + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("[Form] Wirte_Net_Stat 오류 : " + E + Environment.NewLine);
                }
            }
        }

        private void Form_Shown(object sender, EventArgs e) //Form 나타날때, 동작 함수
        {

            string ReturnValue = iCos4Connect();

            if (ReturnValue == "SUCCESS")
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Successful iCOS connection");
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Successful iCOS connection" + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("iCOS 접속 성공");
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " iCOS 접속 성공" + Environment.NewLine);
                }

                EndTxt.Clear();
                StartTxt.Text = Convert.ToString(DateTime.Now);

                Conn_iCos_Btn.Enabled = false;
                ProStartBtn.Enabled = false;
                ProStopBtn.Enabled = true;

                PointSetBtn.Enabled = true;
                PointUnRegBtn.Enabled = false;

                FileSettingBtn.Enabled = false;
                FileMatchBtn.Enabled = false;
                FileExpBtn.Enabled = false;
                //PointSetBtn.PerformClick();
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " iCOS connection failed" + Environment.NewLine);
                    LFC.Log("iCOS connection failed" + Environment.NewLine);
                }
                else//한글
                {
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " iCOS 접속 실패" + Environment.NewLine);
                    LFC.Log("iCOS 접속 실패" + Environment.NewLine);
                }
            }
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
        }

        public void ProStartBtn_Click(object sender, EventArgs e) //시작 버튼 클릭 함수
        {
            int nNet = Convert.ToInt32(iCosSocket.GetConnectionStatus(szICOS_ID));
            string strRet = nNet.ToString();
            if (strRet == "1")
            {
                //FolderBrowserDialog();
                //if (toolStripStatusLabel1.Text != "")
                //{
                try
                {
                    FirstCheck FC = new FirstCheck();
                    string returnvalue = FC.Check_DailyData(); // Hour, Daily 테이블 삽입 및 업데이트

                    if (returnvalue == "error")
                    {
                        if (Enable_EnglishMode)//영어
                        {
                            LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Program DB connection error" + Environment.NewLine);
                            LFC.Log("[Form] Program DB connection error" + Environment.NewLine);
                        }
                        else//한글
                        {
                            LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 프로그램 DB 접속 오류" + Environment.NewLine);
                            LFC.Log("[Form] 프로그램 DB 접속 오류" + Environment.NewLine);
                        }
                        return;
                    }

                    EndTxt.Clear();
                    StartTxt.Text = Convert.ToString(DateTime.Now);

                    ProStartBtn.Enabled = false; // 시작버튼 비활성화.
                    ProStopBtn.Enabled = true;
                    FileSettingBtn.Enabled = false;
                    FileMatchBtn.Enabled = false;
                    FileExpBtn.Enabled = false;
                    AllValueCheck_btn.Enabled = true;
                    RequestValue_btn.Enabled = true;

                    OneMinute_Insert OMI = new OneMinute_Insert();
                    OMI.Today_PeakMinMax();
                    OMI.Year_PeakMinMax();

                    MTT.timer2start();
                    if (Enable_EnglishMode)//영어
                    {
                        LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Start DGW operation" + Environment.NewLine);
                        LFC.Log("[Form] Start DGW operation" + Environment.NewLine);
                    }
                    else//한글
                    {
                        LogTxt.AppendText(Convert.ToString(DateTime.Now) + " DGW 작동 시작" + Environment.NewLine);
                        LFC.Log("[Form] DGW 작동 시작" + Environment.NewLine);
                    }
                }
                catch (Exception eProStart)
                {
                    if (Enable_EnglishMode)//영어
                    {
                        LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Program DB connection error" + Environment.NewLine);
                        LFC.Log("[Form] Program DB connection error" + Environment.NewLine);
                    }
                    else//한글
                    {
                        LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 프로그램 DB 접속 오류 : " + eProStart + Environment.NewLine);
                        LFC.Log("[Form] 프로그램 DB 접속 오류 : " + eProStart + Environment.NewLine);
                    }
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Not connected to ICOS" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Not connected to ICOS" + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("ICOS와 연결 되지 않았습니다." + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " ICOS와 연결 되지 않았습니다." + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }

        private void ProStopBtn_Click(object sender, EventArgs e) //스탑 버튼 클릭 함수
        {
            try
            {
                ProStartBtn.Enabled = true;
                ProStopBtn.Enabled = false;

                FileSettingBtn.Enabled = true;
                FileMatchBtn.Enabled = true;
                FileExpBtn.Enabled = true;

                EndTxt.Text = Convert.ToString(DateTime.Now);
                if (Enable_EnglishMode)//영어
                {
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Abort the program" + Environment.NewLine);
                    LFC.Log("Abort the program" + Environment.NewLine);
                }
                else//한글
                {
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 프로그램 중단" + Environment.NewLine);
                    LFC.Log("프로그램 중단" + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();

                MTT.timer2Stop();
            }
            catch (Exception ex)
            {

                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Program interruption error : " + ex + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("프로그램 중단 오류 : " + ex + Environment.NewLine);
                }
            }
        }

        private void ProSetBtn_Click(object sender, EventArgs e) //접속 설정 클릭 함수
        {
            SettingForm SF = new SettingForm();
            SF.Text = (Enable_EnglishMode ? "setup" : "설정");
            SF.label11.Text = (Enable_EnglishMode ? "BEMS database" : "BEMS 데이타베이스");
            SF.label12.Text = (Enable_EnglishMode ? "MMI connect" : "MMI 접속");
            SF.label9.Text = (Enable_EnglishMode ? "Air conditioning period" : "냉방기간");
            SF.label16.Text = (Enable_EnglishMode ? "Heating period" : "난방기간");
            SF.SettingFormSave.Text = (Enable_EnglishMode ? "Save" : "저장");
            SF.SettingFormExit.Text = (Enable_EnglishMode ? "Close" : "닫기");
            SF.ShowDialog();
        }

        private void ProPathBtn_Click(object sender, EventArgs e)//프로젝트 설정 클릭 함수
        {
            System.Diagnostics.Process.Start("explorer.exe", Environment.CurrentDirectory);
        }

        /// <summary>
        /// 셋팅파일 불러오기 버튼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FileSettingBtn_Click(object sender, EventArgs e)
        {
            string FSBLocation = Environment.CurrentDirectory + "\\Login.ini";

            try
            {
                System.Diagnostics.Process.Start(FSBLocation);
            }
            catch
            {
                FileError(FSBLocation);
            }
        }

        /// <summary>
        /// 매칭파일 불러오기 버튼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FileMatchBtn_Click(object sender, EventArgs e)
        {
            string FSBLocation = Environment.CurrentDirectory + "\\SettingFile.csv";
            try
            {
                System.Diagnostics.Process.Start(FSBLocation);
            }
            catch
            {
                FileError(FSBLocation);
            }
        }

        /// <summary>
        /// 수식파일 불러오기 버튼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FileExpBtn_Click(object sender, EventArgs e)
        {
            string FSBLocation = Environment.CurrentDirectory + "\\Expression.csv";
            try
            {
                System.Diagnostics.Process.Start(FSBLocation);
            }
            catch
            {
                FileError(FSBLocation);
            }
        }

        public void FileError(string Error) // 파일 읽어오기 에러 확인 삼수
        {
            if ((!Error.Contains("Login.ini")) || (!Error.Contains("expression.csv")) || (!Error.Contains("Matching.csv")))
            {
                if (Enable_EnglishMode)//영어
                {
                    MessageBox.Show("File not found");
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + "  File not found" + Environment.NewLine);
                    LFC.Log("File not found : " + Environment.NewLine);
                }
                else//한글
                {
                    MessageBox.Show("파일을 찾을 수 없음");
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + "  파일을 찾을 수 없음" + Environment.NewLine);
                    LFC.Log("파일을 찾을 수 없음 : " + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }

        public void FolderBrowserDialog()
        {
            toolStripStatusLabel1.Text = Environment.CurrentDirectory;

            if (Enable_EnglishMode)//영어
            {
                LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Routing complete" + Environment.NewLine);
                LogTxt.AppendText(toolStripStatusLabel1 + Environment.NewLine);

                LFC.Log("Routing complete : " + toolStripStatusLabel1 + Environment.NewLine);
            }
            else//한글
            {
                LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 경로 설정 완료" + Environment.NewLine);
                LogTxt.AppendText(toolStripStatusLabel1 + Environment.NewLine);

                LFC.Log("경로 설정 완료 : " + toolStripStatusLabel1 + Environment.NewLine);
            }
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
        }

        private void EraseLog_Click(object sender, EventArgs e) // 로그 박스에 로그 기록 삭제 함수
        {
            LogTxt.Clear();
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
        }

        private void Form_FormClosing(object sender, FormClosingEventArgs e)// 프로그램 종료 이벤트
        {
            if (MessageBox.Show((Enable_EnglishMode ? "Do you want to exit the program?" : "프로그램을 종료하시겠습니까?"), (Enable_EnglishMode ? "End" : "종료"), MessageBoxButtons.YesNo) == DialogResult.Yes)
            {

                if (MTT.timer2 != null)
                    MTT.timer2Stop();
                Application.ExitThread();

                for (int i = 0; i < 1000000; i++) {; }
                // 프로세스 종료
                Application.Exit();

                // 프로세스가 남아있다면 최종 종료 (2개의 프로젝트가 공존하고 Application.ProductName 값이 2개다

                System.Diagnostics.Process[] mProcess = System.Diagnostics.Process.GetProcessesByName(Application.ProductName);
                foreach (System.Diagnostics.Process p in mProcess)
                    p.Kill();
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("The program has been terminated by the user." + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("사용자에 의해 프로그램이 종료되었습니다." + Environment.NewLine);
                }
                // 최종 정리 (보완코드 : 크로스 스레드 문제 발생 여지가 있으므로 사용주의)            
                Environment.Exit(0);
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Program termination canceled by user.");
                }
                else//한글
                {
                    LFC.Log("사용자에 의해 프로그램 종료가 취소되었습니다.");
                }
                e.Cancel = true;
                return;
            }
        }

        private void PointSetBtn_Click(object sender, EventArgs e) //관제점 등록 함수
        {
            int nNet = Convert.ToInt32(iCosSocket.GetConnectionStatus(szICOS_ID));
            string strRet = nNet.ToString();

            if (strRet == "1")
            {
                ReadTag(); //관제점 등록
                Conn_iCos_Btn.Enabled = false;
                AllValueCheck_btn.Enabled = true;
                RequestValue_btn.Enabled = true;
                ProStartBtn.Enabled = true;
                PointUnRegBtn.Enabled = true;
                PointSetBtn.Enabled = false;
                ProStartBtn.PerformClick();
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Not connected to ICOS." + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Not connected to ICOS." + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("ICOS와 연결 되지 않았습니다." + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " ICOS와 연결 되지 않았습니다." + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }

        private void Conn_iCos_Btn_Click(object sender, EventArgs e) //iCOS 연결 클릭 함수
        {
            string ReturnValue = iCos4Connect(); //iCOS 연결

            if (ReturnValue == "SUCCESS")
            {
                StartTxt.Text = Convert.ToString(DateTime.Now);
                EndTxt.Clear();

                Conn_iCos_Btn.Enabled = false;
                ProStartBtn.Enabled = false;
                ProStopBtn.Enabled = true;

                PointSetBtn.Enabled = true;
                PointUnRegBtn.Enabled = true;
                //PointSetBtn.PerformClick();
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Successful iCOS connection" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Successful iCOS connection" + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("iCOS 접속 성공" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " iCOS 접속 성공" + Environment.NewLine);
                }
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("iCOS connection failed" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " iCOS connection failed" + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("iCOS 접속 실패" + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " iCOS 접속 실패" + Environment.NewLine);
                }
            }
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
        }

        private void PointUnRegBtn_Click(object sender, EventArgs e) //관제점 해제 클릭 함수
        {
            int nNet = Convert.ToInt32(iCosSocket.GetConnectionStatus(szICOS_ID));
            string strRet = nNet.ToString();
            if (strRet == "1")
            {
                int i = UnReg(); //관제점 해제
                if (i == 1)
                {
                    PointUnRegBtn.Enabled = false;
                    AllValueCheck_btn.Enabled = false;
                    RequestValue_btn.Enabled = false;
                    ProStartBtn.Enabled = false;
                    PointSetBtn.Enabled = true;
                    ProStopBtn.PerformClick();
                }
                else
                {
                    PointUnRegBtn.Enabled = true;
                }
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    LFC.Log("Not connected to ICOS." + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Not connected to ICOS." + Environment.NewLine);
                }
                else//한글
                {
                    LFC.Log("ICOS와 연결 되지 않았습니다." + Environment.NewLine);
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " ICOS와 연결 되지 않았습니다." + Environment.NewLine);
                }
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }

        private void Btn_TagSetFile_Click(object sender, EventArgs e) //TagSetFile 클릭 함수, TagSetFile 파일 생성
        {
            Creating_Setting_File CSF = new Creating_Setting_File();
            CSF.Create_Point_File();
        }

        private void Btn_SettingFile_Click(object sender, EventArgs e)//SettingFile 클릭 함수, SettingFile 파일 생성
        {
            Creating_Setting_File CSF = new Creating_Setting_File();
            CSF.Create_Setting_Point_File();
        }

        private void AllValueCheck_btn_Click(object sender, EventArgs e)//일괄 출력 클릭 함수
        {
            string[] sArray = File.ReadAllLines("TagSetFile.csv", Encoding.Default);

            if (Enable_EnglishMode)//영어
            {
                LogTxt.AppendText("*** current time : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
                LFC.Log("*** current time : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
            }
            else//한글
            {
                LogTxt.AppendText("*** 현재 시간 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
                LFC.Log("*** 현재 시간 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
            }

            try
            {
                for (int i = 0; i < sArray.Length; i++)
                {
                    string[] tmp = sArray[i].Split(','); // tmp[0] = index, tmp[1] = Tag명.
                    if (Enable_EnglishMode)//영어
                    {
                        LogTxt.AppendText('"' + tmp[1] + '"' + " value : " + iCosSocket.IcosGetTagValue(tmp[1]) + Environment.NewLine);
                        LFC.Log('"' + tmp[1] + '"' + " value : " + iCosSocket.IcosGetTagValue(tmp[1]));
                    }
                    else//한글
                    {
                        LogTxt.AppendText('"' + tmp[1] + '"' + " 의 값 : " + iCosSocket.IcosGetTagValue(tmp[1]) + Environment.NewLine);
                        LFC.Log('"' + tmp[1] + '"' + " 의 값 : " + iCosSocket.IcosGetTagValue(tmp[1]));
                    }
                }
                LogTxt.AppendText("**********************************" + Environment.NewLine);
                LFC.Log("**********************************" + Environment.NewLine);
            }
            catch (Exception er)
            {
                if (Enable_EnglishMode)//영어
                {
                    MessageBox.Show("Error occurred");
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Error occurred : " + er);
                    LFC.Log("Error occurred = " + er);
                }
                else//한글
                {
                    MessageBox.Show("오류 발생");
                    LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 오류 발생 : " + er);
                    LFC.Log("오류 발생 = " + er);
                }
            }
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
        }

        private void RequestValue_btn_Click(object sender, EventArgs e) //특정 값 출력 함수
        {
            if (RequestValue.Text != "")
            {
                if (Enable_EnglishMode)//영어
                {
                    LogTxt.AppendText("*** current time : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
                    LFC.Log("*** current time : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
                }
                else//한글
                {
                    LogTxt.AppendText("*** 현재 시간 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
                    LFC.Log("*** 현재 시간 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***" + Environment.NewLine);
                }
                try
                {
                    string tmp = RequestValue.Text; //태그값
                    if (Enable_EnglishMode)//영어
                    {
                        LogTxt.AppendText('"' + tmp + '"' + " value : " + iCosSocket.IcosGetTagValue(tmp) + Environment.NewLine);
                        LFC.Log(tmp + " value : " + iCosSocket.IcosGetTagValue(tmp) + Environment.NewLine);
                    }
                    else//한글
                    {
                        LogTxt.AppendText('"' + tmp + '"' + " 의 값 : " + iCosSocket.IcosGetTagValue(tmp) + Environment.NewLine);
                        LFC.Log(tmp + " 의 값 : " + iCosSocket.IcosGetTagValue(tmp) + Environment.NewLine);
                    }
                    LogTxt.AppendText("**********************************" + Environment.NewLine);
                    LFC.Log("**********************************" + Environment.NewLine);
                }
                catch (Exception er)
                {
                    if (Enable_EnglishMode)//영어
                    {
                        MessageBox.Show("Error occurred");
                        LogTxt.AppendText(Convert.ToString(DateTime.Now) + " Error occurred : " + er);
                        LFC.Log("Error occurred : " + er);
                    }
                    else//한글
                    {
                        MessageBox.Show("오류 발생");
                        LogTxt.AppendText(Convert.ToString(DateTime.Now) + " 오류 발생 : " + er);
                        LFC.Log("오류 발생 : " + er);
                    }
                }
            }
            else
            {
                if (Enable_EnglishMode)//영어
                {
                    MessageBox.Show("No confirmation value.");
                }
                else//한글
                {
                    MessageBox.Show("확인 값이 없습니다.");
                }
                return;
            }
            LogTxt.Select(LogTxt.Text.Length, 0);
            LogTxt.ScrollToCaret();
        }

        private void RequestValue_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 8) //백스페이스할때, 데이터 삭제
            {
                if (RequestValue.Text.Length != 0)
                {
                    RequestValue.Text = RequestValue.Text.Substring(0, RequestValue.Text.Length - 1);
                    RequestValue.Select(RequestValue.Text.Length, 0);
                    e.Handled = true;
                }
                else
                {
                    e.Handled = true;
                }
            }
            else
            {
                RequestValue.Select(RequestValue.Text.Length, 0); //현재 데이터 뒤로 포커스 이동
            }
        }
        private void RequestValue_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A) //Ctrl + A 동작
            {
                ((TextBox)sender).SelectAll();
            }
            if (e.Control && e.KeyCode == Keys.C) //Ctrl + C 동작
            {
                ((TextBox)sender).Copy();
            }
            if (e.Control && e.KeyCode == Keys.V) //Ctrl + V 동작
            {
                ((TextBox)sender).Paste();
            }
            if (e.Control && e.KeyCode == Keys.X) //Ctrl + X 동작
            {
                ((TextBox)sender).Cut();
            }
        }

        private void LogTxt_TextChanged(object sender, EventArgs e)
        {
            if (LogTxt.Lines.Length >= 5000)
            {
                LogTxt.Clear();
                LogTxt.Select(LogTxt.Text.Length, 0);
                LogTxt.ScrollToCaret();
            }
        }
    }
}
