using System;
using System.IO;
using System.IO.Ports;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Timers;
using System.Threading;
using System.Diagnostics;
using System.Media;
// txt2comport.exe
// ทำงานแบบ Windows Application 

namespace Original
{
    public class MyGlobal
    {
        public static string cpFlag;
        public static string cpCom;
        public static string cpType;
        public static string cpFileText;
        public static string cFoldLink;
        public static string cHistory="0";
        public static int nFileType = 0;
        public static bool lInForm=false;
    }

    // Window Form Pipop
    public class WLoop : Form
    {
        private static System.Timers.Timer runTimer;
        public Button button1, button2;
        public static Label  ctext1, ctext2, ctextF;
        public static Int32 nCount = 1;
        public static DateTime dStartDate = DateTime.Now;

        public WLoop()
        {
            MyGlobal.cpFlag = "1";
            this.Size = new System.Drawing.Size(500, 150);
            this.ControlBox = false;
            this.TopMost = true;
            this.AutoScroll = false;
            this.Text = "เปิด | ปิดไฟ";
            // this.StartPosition = FormStartPosition.CenterScreen;
            ctext1 = new Label();
            ctext1.Location = new Point(5, 40);
            ctext1.AutoSize = true;
            this.Controls.Add(ctext1);
            ctext2 = new Label();
            ctext2.Location = new Point(5, 65);
            ctext2.AutoSize = true;
            this.Controls.Add(ctext2);
            ctextF = new Label();
            ctextF.Location = new Point(5, 90);
            ctextF.AutoSize = true;
            this.Controls.Add(ctextF);
            foreach (Control cTextAll in this.Controls)
            {
                if (cTextAll is Label)
                {
                    cTextAll.Font = new Font("Tahoma", 12, FontStyle.Bold);
                    cTextAll.ForeColor = Color.Blue;
                }
            }
            ctextF.Text = MyGlobal.cpCom+","+MyGlobal.cFoldLink;
            if (MyGlobal.cHistory == "1") { ctextF.Text = ctextF.Text + " ,เก็บประวัติ"; }
            else { ctextF.Text = ctextF.Text + " ,ไม่เก็บประวัติ"; }
            ctextF.Text = ctextF.Text + " (txt2com.ini)";
            ctext1.Text = "รอรับคำสั่งแรก"; ctext2.Text = ">>>"; 
            button1 = new Button();
            button1.Size = new Size(100, 30);
            button1.Location = new Point(0, 5);
            button1.Enabled = true;
            button1.Text = "MINIMIZE";
            button1.Font = new Font("Tahoma", 12, FontStyle.Bold);
            this.Controls.Add(button1);
            button1.Click += new EventHandler(button1_Click);
            button2 = new Button();
            button2.Size = new Size(100, 30);
            button2.Location = new Point(101, 5);
            button2.Enabled = true;
            button2.Text = "EXIT";
            button2.Font = new Font("Tahoma", 12, FontStyle.Bold);
            this.Controls.Add(button2);
            button2.Click += new EventHandler(button2_Click);
            MyGlobal.lInForm = true;
            Settimer();
        }

        private void button1_Click(object sender, EventArgs e)
        {
              this.WindowState = FormWindowState.Minimized;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private static void Settimer()
        {
            runTimer = new System.Timers.Timer(5 * 1000); // nSecond วินาที
            runTimer.Elapsed += OnTimedEvent;
            runTimer.AutoReset = true;
            runTimer.Enabled = true;
        }

        static void uYodTimeWait(int ms)
        {
            Console.WriteLine("Wait .....");
            ms = ms * 1000;
            DateTime start = DateTime.Now;
            while ((DateTime.Now - start).TotalMilliseconds < ms)
                Application.DoEvents();
        }


        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            if (!Directory.Exists(MyGlobal.cFoldLink)) { Directory.CreateDirectory(MyGlobal.cFoldLink); }
            SoundPlayer POKSound = new SoundPlayer("C:\\Windows\\Media\\Speech On.wav");
            DirectoryInfo driMach = new DirectoryInfo(MyGlobal.cFoldLink);
            FileInfo[] File_txtmach = driMach.GetFiles("*.txt");
            // หยุดเวลา 
            runTimer.Stop();
            runTimer.Enabled = false;
            foreach (FileInfo cfile in File_txtmach)
            {
                MyGlobal.cpFileText = cfile.Name;
                ctext1.Text = cfile.Name.ToLower();
                ctext2.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                // Pipop  L
                switch (MyGlobal.cpType)
                {
                    case ("2"):
                        Program.Control_2(MyGlobal.cpFileText, 2);
                        Program.Control_2(MyGlobal.cpFileText, 9);
                        break;
                    case ("3"):
                        Program.Control_3(MyGlobal.cpFileText);
                        break;
                    case ("4"):
                        Program.Control_4(MyGlobal.cpFileText, 2);
                        Program.Control_4(MyGlobal.cpFileText, 9);
                        break; 
                    case ("5"):
                        Program.Control_56(1,MyGlobal.cpFileText);
                        break;
                    case ("6"):
                        Program.Control_56(2, MyGlobal.cpFileText);
                        break;
                    default:
                        Program.Control_1(MyGlobal.cpFileText);
                        break;
                }
                POKSound.Play();
                ctext1.Text = ctext1.Text+" รออ่านไฟล์ต่อไป ";
                uYodTimeWait(2);
                File.Delete(cfile.FullName);
            }
            // ทำงานต่อ  
            nCount++;
            ctext1.Text = "รอรับคำสั่งชุดที่ "+nCount;
            runTimer.Enabled = true;
            runTimer.Start();
            TimeSpan ts = (DateTime.Now - dStartDate);
            ctext2.Text = "ใช้เวลาไปแล้ว "+ts.ToString();
        }
    }
    // Window Form 

    static class Program  // Pipop
    {
        public static string MyProg = "uyodbackup".ToLower();
        private static string fBackupTxt = "";
        public static int nForWork = 1;
        public static string cFleWorkAct = "";  // ไว้ในในอนาคต ต่อไป 
        public static bool insource = false;
        /// <summary>
        [STAThread]

        static void Txt2ComReadMe()
        {
            if (!File.Exists("txt2combat.bat"))
            {
                TextWriter WriteTxt1 = new StreamWriter("txt2combat.bat");
                WriteTxt1.WriteLine("Cls");
                WriteTxt1.WriteLine("Rem Sample");
                WriteTxt1.WriteLine("Rem txt2com 0 com? 2 :M0101");
                WriteTxt1.WriteLine("Rem txt2com 0 com? 2 test.txt");
                WriteTxt1.WriteLine("Rem Type Exit For Exit");
                WriteTxt1.WriteLine("Cmd");
                WriteTxt1.Close();
            }
            string cFileDate = "";
            if (File.Exists("original.exe")) { cFileDate = File.GetLastWriteTime("original.exe").ToString(); }
            if (File.Exists("txt2com.exe")) { cFileDate = File.GetLastWriteTime("txt2com.exe").ToString(); }
            var nYesno = MessageBox.Show("วันที่โปรแกรม " + cFileDate + System.Environment.NewLine + System.Environment.NewLine
        + "txt2com 0 COM? n FT ---> แสดงค่าด้วยและส่งตรงๆ " + System.Environment.NewLine
        + "txt2com 1 COM? n FT ---> ส่งตรงๆ " + System.Environment.NewLine
        + "txt2com L COM? n 0 ---> ส่งแบบวนลูปรับค่าtext " + System.Environment.NewLine
        + "n= 1-6 " + System.Environment.NewLine
        + "FT = ไฟล์หรือข้อความ" + System.Environment.NewLine + System.Environment.NewLine
        + "เลือก Yes เพื่อเข้า DOS และ เวบ"
        , "", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
            if (nYesno == DialogResult.Yes) { Process.Start("txt2combat.bat"); OpenWebSite("uyod.net/pdf/txt2com.pdf"); }
        }

        static void OpenWebSite(String URLname)
        {
            string FleBrowser = "iexplore.exe";
            if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe"))
            { FleBrowser = "firefox.exe"; }
            if (File.Exists(@"C:\Program Files\Google\Chrome\Application\chrome.exe"))
            { FleBrowser = "chrome.exe"; }
            var opentwebthis = new ProcessStartInfo(FleBrowser);
            opentwebthis.Arguments = URLname;
            Process.Start(opentwebthis);
        }


        public static void Control_1(string cTxtFile) // รับได้ทั้งข้อความและ *.txt 
        {
            try
            {
                SerialPort dPort = new SerialPort();
                dPort.PortName = MyGlobal.cpCom;
                dPort.BaudRate = 9600;
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                dPort.Open();
                switch (MyGlobal.nFileType)
                {
                    case (2):
                        string[] lines = File.ReadAllLines(cTxtFile);
                        foreach (string linein in lines)
                        {
                            dPort.WriteLine(linein.Trim());
                            if (MyGlobal.cpFlag == "0")
                            {
                                Util.Program.Pok_Mess("File : " + cTxtFile + System.Environment.NewLine + System.Environment.NewLine
                                + "Command " + linein.Trim());
                            }
                        }
                        break;
                    default:
                        dPort.WriteLine(cTxtFile);
                        break;
                }
                dPort.Close(); dPort.Dispose();
                if (MyGlobal.cpFlag == "0")
                { Util.Program.Pok_Mess("ส่ง " + cTxtFile + " แบบที่ " + MyGlobal.cpType + " -ไปที่ " + MyGlobal.cpCom + " สำเร็จ"); }
                if (MyGlobal.cHistory == "1") { SaveHistory(1, cTxtFile); }
            }
            catch
            { ErrorInCOM(); }
        }


        public static void Control_2(string cTxtFile, int nRate) // สำหรับระบบ อำพันได้  
        {
            try
            {
                SerialPort dPort = new SerialPort();
                dPort.PortName = MyGlobal.cpCom;
                switch (nRate)
                {
                    case (2): dPort.BaudRate = 2400; break;
                    default: dPort.BaudRate = 9600; break;
                }
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                dPort.Open();
                using (FileStream fileStream = new FileStream(cTxtFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryReader binary = new BinaryReader(fileStream, Encoding.GetEncoding(28591));
                    dPort.Write(binary.ReadBytes((int)fileStream.Length), 0, (int)fileStream.Length);
                }
                dPort.Close(); dPort.Dispose();
                if (MyGlobal.cpFlag == "0")
                {
                    Util.Program.Pok_Mess("ส่ง " + cTxtFile + " แบบที่ " + MyGlobal.cpType + " -ไปที่ " + MyGlobal.cpCom
                        + " สำเร็จ" + " ->" + dPort.BaudRate.ToString());
                }
                if (MyGlobal.cHistory == "1") { SaveHistory(1, cTxtFile); }
            }
            catch
            { ErrorInCOM(); }
        }


        public static void Control_3(string cTxtFile)
        {
            if (MyGlobal.nFileType == 0) { Util.Program.Pok_Mess("รับได้เฉพาะไฟล์นามสกุล .txt เท่านั้น"); }
            try
            {
                SerialPort dPort = new SerialPort();
                dPort.PortName = MyGlobal.cpCom;
                dPort.BaudRate = 9600;
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                dPort.Open();
                using (TextReader reader = File.OpenText(MyGlobal.cpFileText))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        dPort.WriteLine(line);
                    }
                }
                dPort.Close(); dPort.Dispose();
                if (MyGlobal.cpFlag == "0")
                { Util.Program.Pok_Mess("ส่ง " + cTxtFile + " แบบที่ " + MyGlobal.cpType + " -ไปที่ " + MyGlobal.cpCom + " สำเร็จ"); }
                if (MyGlobal.cHistory == "1") { SaveHistory(1, cTxtFile); }
            }
            catch
            { ErrorInCOM(); }
        }


        public static void Control_4(string cTxtFile, int nRate) // สำหรับระบบ อำพันได้  
        {
            try
            {
                SerialPort dPort = new SerialPort();
                dPort.PortName = MyGlobal.cpCom;
                switch (nRate)
                {
                    case (2): dPort.BaudRate = 2400; break;
                    default: dPort.BaudRate = 9600; break;
                }
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                dPort.Open();
                dPort.Write(File.OpenText(cTxtFile).ReadToEnd());
                dPort.Close(); dPort.Dispose();
                if (MyGlobal.cpFlag == "0")
                {
                    Util.Program.Pok_Mess("ส่ง " + cTxtFile + " แบบที่ " + MyGlobal.cpType + " -ไปที่ "
                      + MyGlobal.cpCom + " สำเร็จ" + " ->" + dPort.BaudRate.ToString());
                }
                if (MyGlobal.cHistory == "1") { SaveHistory(1, cTxtFile); }
            }
            catch
            { ErrorInCOM(); }
        }



        static void CalRelay5(string txt,ref int n1, ref int n2, ref int n3, ref int n4, ref int n5, ref int n6, ref int n7, ref int n8)
        {
            switch (txt)
            {
                case ("01011"): n1 = 1; n2 = 6; n3 = 0; n4 = 1; n5 = 1; n6 = 0; n7 = 217; n8 = 154;  break;
                case ("01010"): n1 = 1; n2 = 6; n3 = 0; n4 = 1; n5 = 2; n6 = 0; n7 = 217; n8 = 106; break;
                case ("01021"): n1 = 1; n2 = 6; n3 = 0; n4 = 2; n5 = 1; n6 = 0; n7 = 41; n8 = 154; break;
                case ("01020"): n1 = 1; n2 = 6; n3 = 0; n4 = 2; n5 = 2; n6 = 0; n7 = 41; n8 = 106; break;
                case ("01031"): n1 = 1; n2 = 6; n3 = 0; n4 = 3; n5 = 1; n6 = 0; n7 = 120; n8 = 90; break;
                case ("01030"): n1 = 1; n2 = 6; n3 = 0; n4 = 3; n5 = 2; n6 = 0; n7 = 120; n8 = 170; break;
                case ("01041"): n1 = 1; n2 = 6; n3 = 0; n4 = 4; n5 = 1; n6 = 0; n7 = 201; n8 = 155; break;
                case ("01040"): n1 = 1; n2 = 6; n3 = 0; n4 = 4; n5 = 2; n6 = 0; n7 = 201; n8 = 107; break;
                case ("01051"): n1 = 1; n2 = 6; n3 = 0; n4 = 5; n5 = 1; n6 = 0; n7 = 152; n8 = 91; break;
                case ("01050"): n1 = 1; n2 = 6; n3 = 0; n4 = 5; n5 = 2; n6 = 0; n7 = 152; n8 = 171; break;
                case ("01061"): n1 = 1; n2 = 6; n3 = 0; n4 = 6; n5 = 1; n6 = 0; n7 = 104; n8 = 91; break;
                case ("01060"): n1 = 1; n2 = 6; n3 = 0; n4 = 6; n5 = 2; n6 = 0; n7 = 104; n8 = 171; break;
                case ("01071"): n1 = 1; n2 = 6; n3 = 0; n4 = 7; n5 = 1; n6 = 0; n7 = 57; n8 = 155; break;
                case ("01070"): n1 = 1; n2 = 6; n3 = 0; n4 = 7; n5 = 2; n6 = 0; n7 = 57; n8 = 107; break;
                case ("01081"): n1 = 1; n2 = 6; n3 = 0; n4 = 8; n5 = 1; n6 = 0; n7 = 9; n8 = 152; break;
                case ("01080"): n1 = 1; n2 = 6; n3 = 0; n4 = 8; n5 = 2; n6 = 0; n7 = 9; n8 = 104; break;

                case ("02011"): n1 = 2; n2 = 6; n3 = 0; n4 = 1; n5 = 1; n6 = 0; n7 = 217; n8 = 169; break;
                case ("02010"): n1 = 2; n2 = 6; n3 = 0; n4 = 1; n5 = 2; n6 = 0; n7 = 217; n8 = 89; break;
                case ("02021"): n1 = 2; n2 = 6; n3 = 0; n4 = 2; n5 = 1; n6 = 0; n7 = 41; n8 = 169; break;
                case ("02020"): n1 = 2; n2 = 6; n3 = 0; n4 = 2; n5 = 2; n6 = 0; n7 = 41; n8 = 89; break;
                case ("02031"): n1 = 2; n2 = 6; n3 = 0; n4 = 3; n5 = 1; n6 = 0; n7 = 120; n8 = 105; break;
                case ("02030"): n1 = 2; n2 = 6; n3 = 0; n4 = 3; n5 = 2; n6 = 0; n7 = 120; n8 = 153; break;
                case ("02041"): n1 = 2; n2 = 6; n3 = 0; n4 = 4; n5 = 1; n6 = 0; n7 = 201; n8 = 168; break;
                case ("02040"): n1 = 2; n2 = 6; n3 = 0; n4 = 4; n5 = 2; n6 = 0; n7 = 201; n8 = 88; break;
                case ("02051"): n1 = 2; n2 = 6; n3 = 0; n4 = 5; n5 = 1; n6 = 0; n7 = 152; n8 = 104; break;
                case ("02050"): n1 = 2; n2 = 6; n3 = 0; n4 = 5; n5 = 2; n6 = 0; n7 = 152; n8 = 152; break;
                case ("02061"): n1 = 2; n2 = 6; n3 = 0; n4 = 6; n5 = 1; n6 = 0; n7 = 104; n8 = 104; break;
                case ("02060"): n1 = 2; n2 = 6; n3 = 0; n4 = 6; n5 = 2; n6 = 0; n7 = 104; n8 = 152; break;
                case ("02071"): n1 = 2; n2 = 6; n3 = 0; n4 = 7; n5 = 1; n6 = 0; n7 = 57; n8 = 168; break;
                case ("02070"): n1 = 2; n2 = 6; n3 = 0; n4 = 7; n5 = 2; n6 = 0; n7 = 57; n8 = 88; break;
                case ("02081"): n1 = 2; n2 = 6; n3 = 0; n4 = 8; n5 = 1; n6 = 0; n7 = 9; n8 = 171; break;
                case ("02080"): n1 = 2; n2 = 6; n3 = 0; n4 = 8; n5 = 2; n6 = 0; n7 = 9; n8 = 91; break;
            }
        }


        public static void Control_56(int n56, string cTxtF56)  // สำหรับกิ๊บและฮอล
        {
            if (MyGlobal.nFileType == 0) { Control_56_2(n56, cTxtF56); }
            else // มาในรูปแบบ *.txt
            {
                MyGlobal.nFileType = 0; // สำหรับ ข้อความ
                string[] lines = File.ReadAllLines(cTxtF56);
                foreach (string linein in lines)
                {
                    Control_56_2(n56, linein.Trim());
                }
            }
        }


        public static void Control_56_2(int nProg,string cTxtFile)  
        {
            int nCol1, nCol2, nCol3, nCol4, nCol5, nCol6, nCol7, nCol8;
            if (nProg == 2) // สำหรับระบบของ Halls
            {
                if (MyGlobal.nFileType != 0) { Util.Program.Pok_Mess("รับได้เฉพาะตัวเลข 51 หลักเท่านั้น"); return; }
                if (cTxtFile.Length == 0) { return; }
                if (cTxtFile.Length != 5) { Util.Program.Pok_Mess("รับได้เฉพาะตัวเลข 5 หลักเท่านั้น"); return; }
                nCol1 = 0; nCol2 = 0; nCol3 = 0; nCol4 = 0;
                nCol5 = 0; nCol6 = 0; nCol7 = 0; nCol8 = 0;
                CalRelay5(cTxtFile, ref nCol1, ref nCol2, ref nCol3, ref nCol4, ref nCol5, ref nCol6, ref nCol7, ref nCol8);
                if (MyGlobal.cpFlag == "0" && insource)
                {
                    Util.Program.Pok_Mess("cTxtFile = "+cTxtFile + System.Environment.NewLine + System.Environment.NewLine
                      + "nCol1 = " + nCol1.ToString() + System.Environment.NewLine
                      + "nCol2 = " + nCol2.ToString() + System.Environment.NewLine
                      + "nCol3 = " + nCol3.ToString() + System.Environment.NewLine
                      + "nCol4 = " + nCol4.ToString() + System.Environment.NewLine
                      + "nCol5 = " + nCol5.ToString() + System.Environment.NewLine
                      + "nCol6 = " + nCol6.ToString() + System.Environment.NewLine
                      + "nCol7 = " + nCol7.ToString() + System.Environment.NewLine  
                      + "nCol8 = " + nCol8.ToString() + System.Environment.NewLine);
                }
            }
            else // ระบบทั่วไปส่งมา 8 หลัก  
            {
                if (MyGlobal.nFileType != 0) { Util.Program.Pok_Mess("รับได้เฉพาะตัวเลข 8 หลักเท่านั้น"); return; }
                if (cTxtFile.Length == 0) { return; }
                if (cTxtFile.Length != 8) { Util.Program.Pok_Mess("รับได้เฉพาะตัวเลข 8 หลักเท่านั้น"); return; }
                nCol1 = int.Parse(MyGlobal.cpFileText.Substring(0, 1));
                nCol2 = int.Parse(MyGlobal.cpFileText.Substring(1, 1));
                nCol3 = int.Parse(MyGlobal.cpFileText.Substring(2, 1));
                nCol4 = int.Parse(MyGlobal.cpFileText.Substring(3, 1));
                nCol5 = int.Parse(MyGlobal.cpFileText.Substring(4, 1));
                nCol6 = int.Parse(MyGlobal.cpFileText.Substring(5, 1));
                nCol7 = int.Parse(MyGlobal.cpFileText.Substring(6, 1));
                nCol8 = int.Parse(MyGlobal.cpFileText.Substring(7, 1));
            }

            try
            {
                SerialPort dPort = new SerialPort();
                dPort.PortName = MyGlobal.cpCom;
                dPort.BaudRate = 9600;
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                dPort.Open();
                byte[] WordText = new byte[8]
                {
                (byte) nCol1,(byte) nCol2,(byte) nCol3,(byte) nCol4,
                (byte) nCol5,(byte) nCol6,(byte) nCol7,(byte) nCol8
                };
                dPort.Write(WordText, 0, WordText.Length);
                dPort.Close(); dPort.Dispose();
                if (MyGlobal.cpFlag == "0")
                { Util.Program.Pok_Mess("ส่ง " + cTxtFile + " แบบที่ " + MyGlobal.cpType + " -ไปที่ " + MyGlobal.cpCom + " สำเร็จ"); }
                if (MyGlobal.cHistory == "1") { SaveHistory(1, cTxtFile); }
            }
            catch
            { ErrorInCOM();  }
        }


        static void ErrorInCOM()
        {
            SaveHistory(-1, "ส่งแบบที่ " + MyGlobal.cpType + " -ไม่พบ " + MyGlobal.cpCom);
            if (MyGlobal.lInForm)
            {
                MessageBox.Show("พบปัญหา "+MyGlobal.cpCom, "",
                    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
                Application.Exit();
            }
            else
            {
                var nYesno = MessageBox.Show("ส่งแบบที่ " + MyGlobal.cpType + " -ไม่พบ " + MyGlobal.cpCom
                    + System.Environment.NewLine + "กด Yes หา COM ใหม่ที่ใช้ได้", "",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
                if (nYesno == DialogResult.Yes) { CheckComPort(); }
            }
        }


        static void Send_FileTxt() 
        {
            switch (MyGlobal.cpType)
            {
                case ("2"):
                    Control_2(MyGlobal.cpFileText, 2);
                    Control_2(MyGlobal.cpFileText, 9);
                    break;
                case ("3"):
                    Control_3(MyGlobal.cpFileText);
                    break;
                case ("4"):
                    Control_4(MyGlobal.cpFileText, 2);
                    Control_4(MyGlobal.cpFileText, 9);
                    break;
                case ("5"):
                    Control_56(1,MyGlobal.cpFileText);
                    break;
                case ("6"):
                    Control_56(2,MyGlobal.cpFileText);
                    break;
                default:
                    Control_1(MyGlobal.cpFileText);
                    break;
            }
        }


        static void SaveHistory(int nHistory,string txtBackup)
        {
            if (File.Exists("D:\\BdPos\\Txt2Cloud.Txt"))
            {
                string[] lines = File.ReadAllLines("D:\\BdPos\\Txt2Cloud.Txt");
                if (Directory.Exists(lines[3].Trim())) { fBackupTxt = lines[3].Trim(); }
                fBackupTxt = fBackupTxt + "Txt2COM\\";
            }
            else { fBackupTxt = "Txt2COM\\"; }
            if (!Directory.Exists(fBackupTxt)) { Directory.CreateDirectory(fBackupTxt); }
            string cFBackupH = fBackupTxt + DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
            txtBackup = txtBackup + "  " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            switch (nHistory)
            {
                case (-1):
                    txtBackup = "ERROR --> " + txtBackup;
                    cFBackupH = fBackupTxt + "Error "+DateTime.Now.ToString("MM-yyyy") + ".txt";
                    break;
                default:
                    break;
            }
            if (File.Exists(cFBackupH))
            {
                using (StreamWriter Write2Txt2 = File.AppendText(cFBackupH))
                {
                    Write2Txt2.WriteLine(txtBackup);
                    Write2Txt2.Close();
                }
            }
            else
            {
                TextWriter WriteTxt1 = new StreamWriter(cFBackupH);
                WriteTxt1.WriteLine(txtBackup);
                WriteTxt1.Close();
            }
        }


        static void Card_text(string card_num)
        {
            card_num = card_num.Trim().ToLower();
            TextWriter tFleCard_0 = new StreamWriter("card" + card_num + "_0.txt");
            TextWriter tFleCard_1 = new StreamWriter("card" + card_num + "_1.txt");
            string cTxt;
            for (int j = 1; j >= 0; j--)
            {
                for (int i = 1; i <= 16; i++)
                {
                    cTxt = ":M" + card_num + i.ToString().Trim().PadLeft(2, '0') + j.ToString().Trim();
                    if (j == 0) { tFleCard_0.WriteLine(cTxt); }
                    else { tFleCard_1.WriteLine(cTxt); }
                }
            }
            tFleCard_0.Close();
            tFleCard_1.Close();
        }

        static void cr_card() // สร้างไฟล์ card??.txt
        {
            Card_text("01"); Card_text("02"); Card_text("03"); Card_text("04"); Card_text("05");
            Card_text("06"); Card_text("07"); Card_text("08"); Card_text("09"); Card_text("10");
        }


        static void Text2File() // แปลง Text เป็น ไฟล์ 
        {
            if (!Directory.Exists("\\Temp")) { Directory.CreateDirectory("\\Temp"); }
            string cCard = "\\Temp\\t" + DateTime.Now.ToString("HHmmss") + ".txt";
            if (File.Exists(cCard)) { File.Delete(cCard); }
            TextWriter tFleCard = new StreamWriter(cCard);
            if (MyGlobal.cpFileText.Contains(","))
            {
                string[] cutword = MyGlobal.cpFileText.Split(',');
                for (int i = 0; i < cutword.Length; i++)
                { tFleCard.WriteLine(cutword[i]); }
            }
            else { tFleCard.WriteLine(MyGlobal.cpFileText); }
            tFleCard.Close();
            MyGlobal.cpFileText = cCard;
            MyGlobal.nFileType = 1;
        }


        static void CheckComPort()
        {
            TextWriter WriteTxt1 = new StreamWriter("txt2com.set");
            string cComport;
            for (int i = 1; i <= 16; i++)
            {
                cComport = "COM" + i.ToString().Trim();
                try
                {
                    SerialPort cTestPort = new SerialPort();
                    cTestPort.PortName = cComport;
                    cTestPort.Open();
                    cTestPort.WriteLine(":M01011");
                    WriteTxt1.WriteLine(cComport);
                    cTestPort.Close(); cTestPort.Dispose();
                    MyGlobal.cpCom = cComport;
                    Util.Program.Pok_Mess(cComport + " ใช้งานตามปรกติ");
                }
                catch
                {     }
            }
            WriteTxt1.Close();
        }


        static void TestUyod()
        {
            SaveHistory(-1,"TEST");
        }

        static void Main(string[] args)  // Pipop
        {
            nForWork = 1;  //    Pipop ปรกติ  1 nForWork=0 ไม่ทำอะไรเลย ,1 ทำงานตามปรกติ 2 ไม่Runโปรแกรมและมีเตือน  
            if (Directory.Exists(@"R:\Temp")) { insource = true; }  // Run กับ Source
            if (!File.Exists("txt2com.ini"))
            {
                TextWriter WriteTxt1 = new StreamWriter("txt2com.ini");
                WriteTxt1.WriteLine("Ho2Mach         โพลเดอร์ที่เก็บเท็กซ์ไฟล์ จากโปรแกรมโรงแรม");
                WriteTxt1.WriteLine("0               เก็บประวัติข้อมูลเปิดปิดไฟ 0=ไม่เก็บ 1=เก็บ");
                WriteTxt1.WriteLine("");
                WriteTxt1.WriteLine("");
                WriteTxt1.WriteLine("");
                WriteTxt1.Close();
            }
            if (File.Exists("txt2com.ini"))
            {
                string[] inis = File.ReadAllLines("txt2com.ini");
                MyGlobal.cFoldLink = inis[0].Substring(0, 8).Trim();
                MyGlobal.cHistory = inis[1].Substring(0, 1).Trim();
            }
            MyGlobal.cpFlag = ""; MyGlobal.cpCom = ""; MyGlobal.cpType = ""; MyGlobal.cpFileText = "";
            if (args.Length == 0) { Txt2ComReadMe(); return; }
            else
            {
                MyGlobal.cpFlag = args[0].Trim().ToUpper();
                if (MyGlobal.cpFlag == "C") { CheckComPort(); return; }
                if (MyGlobal.cpFlag == "T") { TestUyod(); return; }
                MyGlobal.cpCom = args[1].Trim().ToUpper();
                MyGlobal.cpType = args[2].Trim();
                MyGlobal.cpFileText = args[3].Trim();
                if (MyGlobal.cpFileText.Length <= 4) { MyGlobal.nFileType = 0; }
                else
                {
                    if (MyGlobal.cpFileText.Substring(MyGlobal.cpFileText.Length - 4) == ".txt")
                    {
                        if (MyGlobal.cpFileText.Substring(0, 4) == "card") { MyGlobal.nFileType = 2; }
                        else { MyGlobal.nFileType = 1; }
                    }
                    else { MyGlobal.nFileType = 0; }
                }
            }

            // เช็ค COM0 เพื่อหา COM? อัตโนมัติ 
            if (MyGlobal.cpCom.Substring(3, 1) == "?")
            {
                if (!File.Exists("txt2com.set")) { ErrorInCOM(); }
                string[] lines = File.ReadAllLines("txt2com.set");
                MyGlobal.cpCom = lines[0].Trim().ToUpper();
            }

            if (MyGlobal.nFileType == 0 && (MyGlobal.cpType == "2" || MyGlobal.cpType == "3" || MyGlobal.cpType == "4"))
            { Text2File(); }

            if (MyGlobal.cpFlag == "0") //  || insource
            {
                Util.Program.Pok_Mess("cpFlag=" + MyGlobal.cpFlag
                + System.Environment.NewLine + System.Environment.NewLine
                + ",cpCom  =  " + MyGlobal.cpCom + System.Environment.NewLine
                + ",cpType  =  " + MyGlobal.cpType + System.Environment.NewLine
                + ",cpFileText  =  " + MyGlobal.cpFileText);
            }

            if (!File.Exists("card10_1.txt")) { Util.Program.Pok_Mess("สร้างไฟล์ txt ช่วยงาน"); cr_card(); }  // สร้างไฟล์ card??.txt

            switch (MyGlobal.cpFlag)
            {
                case ("T"): TestUyod(); break;
                case ("0"): Send_FileTxt(); break;
                case ("1"): Send_FileTxt(); break;
                case ("L"):
                    // ตรวจสอบเปิดซ้ำ 
                    Process mobj_pro = Process.GetCurrentProcess();
                    Process[] mobj_proList = Process.GetProcessesByName(mobj_pro.ProcessName);
                    if (mobj_proList.Length > 1)
                    {
                        // MessageBox.Show("เปิดโปรแกรมซ้ำ"); 
                        return;
                    }
                    Application.EnableVisualStyles();
                    Application.Run(new WLoop());
                    break;
            }
        }
    }
}
