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;

namespace txt2com
{
    public class MyGlobal
    {
        public static string cpFlag;
        public static string cpCom;
        public static string cpType;
        public static string cpFileText;
        public static int insource = 0;
        public static int in_pos_prog = 0;
        public static string txtwrite = "AmTech_"+DateTime.Now.ToString("ddMMyyyy")+".txt";
    }


    static class Program
    {
        // private static System.Timers.Timer pokTimer;
        private static int nCount = 0, nSecond = 5;  // ,nLoop=3

        // First 
        public class Form1 : Form
        {
            public Button button1;
            public Label ctext1, ctext2, ctext3, ctext4, ctext5, ctext6;

            public Form1()
            {

                this.Size = new System.Drawing.Size(500, 250);
                // this.FormBorderStyle = FormBorderStyle.None;
                this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
                this.Text = DateTime.Now.ToString("dd/MM/yy hh:mm");

                int ncol = 30, nrow = 20;
                ctext1 = new Label();
                ctext1.Location = new Point(20 + ncol, 20 + nrow);
                ctext1.AutoSize = true;
                this.Controls.Add(ctext1);

                ctext2 = new Label();
                ctext2.Location = new Point(20 + ncol, 45 + nrow);
                ctext2.AutoSize = true;
                this.Controls.Add(ctext2);

                ctext3 = new Label();
                ctext3.Location = new Point(20 + ncol, 70 + nrow);
                ctext3.AutoSize = true;
                this.Controls.Add(ctext3);

                ctext4 = new Label();
                ctext4.Location = new Point(20 + ncol, 95 + nrow);
                ctext4.AutoSize = true;
                this.Controls.Add(ctext4);

                ctext5 = new Label();
                ctext5.Location = new Point(20 + ncol, 120 + nrow);
                ctext5.AutoSize = true;
                this.Controls.Add(ctext5);

                ctext6 = new Label();
                ctext6.Location = new Point(20 + ncol, 130 + nrow);
                ctext6.AutoSize = true;
                this.Controls.Add(ctext6);

                foreach (Control cTextAll in this.Controls)
                {
                    if (cTextAll is Label)
                    {
                        cTextAll.Font = new Font("Tahoma", 12, FontStyle.Regular);
                        cTextAll.ForeColor = Color.White;
                        cTextAll.BackColor = Color.Black;
                    }
                }

                button1 = new Button();
                button1.Size = new Size(80, 20);
                button1.Location = new Point(0, 0);
                button1.Enabled = true;
                button1.Text = "START";
                this.Controls.Add(button1);
                button1.Click += new EventHandler(button1_Click);

                ctext1.Text = "ระบบควบคุมไฟ";
                ctext2.Text = "พัฒนาด้วยภาษา C#";
                ctext3.Text = "โดย UYODTEAM";
                ctext4.Text = "www.Youyod.com";
            }
            private void button1_Click(object sender, EventArgs e)
            {

            }


        }
        // First 


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]

        static void AmpTechReadMe()
        {
            string cFileDate = "";
            if (File.Exists("AmpTech.exe")) { cFileDate = File.GetLastWriteTime("AmpTech.exe").ToString(); }
            MessageBox.Show("วันที่โปรแกรม " + cFileDate + System.Environment.NewLine + System.Environment.NewLine
        + "AmpTech D ---> ยกเลิก " + System.Environment.NewLine
        + "AmpTech L ---> ตรวจสอบการทำงาน " + System.Environment.NewLine
        + "AmpTech 0 COM? n FT ---> แสดงค่าด้วยและส่งตรงๆ " + System.Environment.NewLine
        + "AmpTech 1 COM? n FT ---> ส่งตรงๆ " + System.Environment.NewLine
        + "AmpTech A COM? n 0---> ส่งตามแบบอำพันแบบที่ n " + System.Environment.NewLine
        + "AmpTech M COM? n 0---> ส่งตามแบบอำพันแบบที่ n " + System.Environment.NewLine
        + System.Environment.NewLine + System.Environment.NewLine
        + "n= 1-5 " + System.Environment.NewLine
        + "FT = ไฟล์หรือข้อความ" 
        , "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        static bool RunInSource() // Run ผ่าน Source Code 
        {
            bool lRunInSource;
            if (File.Exists(@"J:\Pipop\Dropbox\Source\AP.ZP"))
            { lRunInSource = true; }
            else { lRunInSource = false; }
            return lRunInSource;
        }

        static void Pok_Mess(string cfWord)
        {
            MessageBox.Show(cfWord + System.Environment.NewLine
            + "" + System.Environment.NewLine
            + "" + System.Environment.NewLine
            , "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        static void Send_FileTxt2COM_1(string cTxtFile)
        {
            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8, StopBits.One);
            port.Handshake = Handshake.None;
            if (port.IsOpen)
            {
                port.Open();
                port.WriteLine(cTxtFile);
                port.Close();
            }
            else { Pok_Mess("ส่งแบบที่ " + MyGlobal.cpType + " -ไม่พบ " + MyGlobal.cpCom); }
        }


        static void Send_FileTxt2COM_2(string cTxtFile)
        {
            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8, StopBits.One);
            port.Handshake = Handshake.None;
            if (port.IsOpen)
            {
                port.Open();
                using (FileStream fileStream = new FileStream(cTxtFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryReader binary = new BinaryReader(fileStream, Encoding.GetEncoding(28591));
                    port.Write(binary.ReadBytes((int)fileStream.Length), 0, (int)fileStream.Length);
                }
                port.Close();
            }
            else { Pok_Mess("ส่งแบบที่ " + MyGlobal.cpType + " -ไม่พบ " + MyGlobal.cpCom); }
        }


        static void Send_FileTxt2COM_3(string cTxtFile)
        {
            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8, StopBits.One);
            port.Handshake = Handshake.None;
            if (port.IsOpen)
            {
                using (TextReader reader = File.OpenText(MyGlobal.cpFileText))
                {
                    string line;

                    while ((line = reader.ReadLine()) != null)
                    {
                        port.WriteLine(line);
                    }
                }
            }
            else { Pok_Mess("ส่งแบบที่ " + MyGlobal.cpType + " -ไม่พบ " + MyGlobal.cpCom); }
        }


        static void Send_FileTxt2COM_4(string cTxtFile)
        {

            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8, StopBits.One);
            port.Handshake = Handshake.None;
            if (port.IsOpen)
            {
                port.Write(File.OpenText(cTxtFile).ReadToEnd());
            }
            else { Pok_Mess("ส่งแบบที่ " + MyGlobal.cpType + " -ไม่พบ " + MyGlobal.cpCom); }
        }

        static void Send_FileTxt2COM_5(string cTxtFile)
        {
            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8, StopBits.One);
            port.Handshake = Handshake.None;
            if (port.IsOpen)
            {
            }
            else { Pok_Mess("ส่งแบบที่ " + MyGlobal.cpType + " -ไม่พบ " + MyGlobal.cpCom); }
        }


        static void Send_FileTxt() // ทำเหมือน Send_FileTxt() และ Amphan2Com()
        {
            if (!File.Exists(MyGlobal.cpFileText)) { Pok_Mess("ไม่พบไฟล์ " + MyGlobal.cpFileText); return; }

            switch (MyGlobal.cpType)
            {
                case ("2"):
                    Send_FileTxt2COM_2(MyGlobal.cpFileText);
                    break;
                case ("3"):
                    Send_FileTxt2COM_3(MyGlobal.cpFileText);
                    break;
                case ("4"):
                    Send_FileTxt2COM_4(MyGlobal.cpFileText);
                    break;
                case ("5"):
                    Send_FileTxt2COM_5(MyGlobal.cpFileText);
                    break;
                default:
                    Send_FileTxt2COM_1(MyGlobal.cpFileText);
                    break;
            }
        }


        static void Amphan2Com()
        {
            switch (MyGlobal.cpType)
            {
                case ("2"):
                    if (File.Exists("txtact.txt")) { Send_FileTxt2COM_2("txtact.txt"); }
                    if (File.Exists("txtact2.txt")) { Send_FileTxt2COM_2("txtact2.txt"); }
                    if (File.Exists("txtact3.txt")) { Send_FileTxt2COM_2("txtact3.txt"); }
                    break;
                case ("3"):
                    if (File.Exists("txtact.txt")) { Send_FileTxt2COM_3("txtact.txt"); }
                    if (File.Exists("txtact2.txt")) { Send_FileTxt2COM_3("txtact2.txt"); }
                    if (File.Exists("txtact3.txt")) { Send_FileTxt2COM_3("txtact3.txt"); }
                    break;
                case ("4"):
                    if (File.Exists("txtact.txt")) { Send_FileTxt2COM_4("txtact.txt"); }
                    if (File.Exists("txtact2.txt")) { Send_FileTxt2COM_4("txtact2.txt"); }
                    if (File.Exists("txtact3.txt")) { Send_FileTxt2COM_4("txtact3.txt"); }
                    break;
                case ("5"):
                    if (File.Exists("txtact.txt")) { Send_FileTxt2COM_5("txtact.txt"); }
                    if (File.Exists("txtact2.txt")) { Send_FileTxt2COM_5("txtact2.txt"); }
                    if (File.Exists("txtact3.txt")) { Send_FileTxt2COM_5("txtact3.txt"); }
                    break;
                default:
                    if (File.Exists("txtact.txt")) { Send_FileTxt2COM_1("txtact.txt"); }
                    if (File.Exists("txtact2.txt")) { Send_FileTxt2COM_1("txtact2.txt"); }
                    if (File.Exists("txtact3.txt")) { Send_FileTxt2COM_1("txtact3.txt"); }
                    break;
            }
        }




        private static void AmPhanAct()
        {
            if (!Directory.Exists("D:\\BdPos"))
            { Pok_Mess("ไม่พบ D:\\BdPos"); File.Copy("Amtech.Txt", "AmpExit.txt"); return; }
            string toCommand;

            DirectoryInfo dri = new DirectoryInfo(@"D:\BdPos");
            FileInfo[] File_txtact = dri.GetFiles("txtact*.txt");
            SoundPlayer POKSound = new SoundPlayer("C:\\Windows\\Media\\Speech On.wav");
            foreach (FileInfo cfile in File_txtact)
                {
                    Thread.Sleep(nSecond * 1000);
                    switch (MyGlobal.cpType)
                    {
                        case ("0"): break;
                        case ("2"): Send_FileTxt2COM_2(cfile.FullName); break;
                        case ("3"): Send_FileTxt2COM_3(cfile.FullName); break;
                        case ("4"): Send_FileTxt2COM_3(cfile.FullName); break;
                        case ("5"): Send_FileTxt2COM_3(cfile.FullName); break;
                        default: Send_FileTxt2COM_1(cfile.FullName); break;
                    }
                    string[] lines = File.ReadAllLines(cfile.FullName);
                    toCommand = lines[0].Trim();
                    toCommand = toCommand.Substring(0, 7);
                    toCommand = "File : " + cfile.FullName +" ,Date: " + DateTime.Now.ToString()+" , "+toCommand;
                    File.AppendAllText(MyGlobal.txtwrite, toCommand+ Environment.NewLine);
                    File.Delete(cfile.FullName);
                    POKSound.Play();
                    nCount++;
                    if (File.Exists("AmpExit.txt")) { break; }
                }

                if (Directory.Exists(@"D:\BdPos\Ho2Mach"))
                {
                    DirectoryInfo driMach = new DirectoryInfo(@"D:\BdPos\Ho2Mach");
                    FileInfo[] File_txtmach = driMach.GetFiles("*.txt");
                    foreach (FileInfo cfile in File_txtmach)
                    {
                        Thread.Sleep(nSecond * 1000);
                        switch (MyGlobal.cpType)
                        {
                            case ("0"): break;
                            case ("2"): Send_FileTxt2COM_2(cfile.FullName); break;
                            case ("3"): Send_FileTxt2COM_3(cfile.FullName); break;
                            case ("4"): Send_FileTxt2COM_3(cfile.FullName); break;
                            case ("5"): Send_FileTxt2COM_3(cfile.FullName); break;
                            default: Send_FileTxt2COM_1(cfile.FullName); break;
                        }
                        string[] lines = File.ReadAllLines(cfile.FullName);
                        toCommand = lines[0].Trim();
                        toCommand = toCommand.Substring(0, 7);
                        toCommand = "File : " + cfile.FullName + " ,Date: " + DateTime.Now.ToString() + " , " + toCommand;
                        File.AppendAllText(MyGlobal.txtwrite, toCommand + Environment.NewLine);
                        File.Delete(cfile.FullName);
                        POKSound.Play();
                        nCount++;
                        if (File.Exists("AmpExit.txt")) { break; }
                    }
                }
        }


        private static void AmphanLoop()
        {
            Form1 AmpWinDows = new Form1();
            AmpWinDows.Show();
            //
            SoundPlayer PokSound = new SoundPlayer();  
            PokSound.SoundLocation="C:\\Windows\\Media\\Alarm01.wav";
            PokSound.Play();
            Thread.Sleep(nSecond * 1000);
            PokSound.SoundLocation = "C:\\Windows\\Media\\Windows Startup.wav"; // chord.wav
            do
            {
                AmPhanAct();
                PokSound.Play();
                Thread.Sleep(nSecond * 1000);
            } while (!File.Exists("AmpExit.txt"));
            // ShowFLtxt(MyGlobal.txtwrite);
        }



        static void ShowFLtxt(string cfFileTxt)
        {
            if (!File.Exists(cfFileTxt)) { MessageBox.Show("ไม่เจอไฟล์ " + cfFileTxt + " กรุณาตรวจสอบ"); return; }
            StreamReader readtext = new StreamReader(cfFileTxt);
            string contents = readtext.ReadToEnd();
            readtext.Close();
            readtext.Dispose();
            MessageBox.Show(contents, "ไฟล์ " + cfFileTxt);
        }

        private static void PrePareVar()
        {
            string cfFile,cfText;
            cfFile = "Amtech.Txt";
            if (!File.Exists(cfFile))
            {
                TextWriter Print2Txt = new StreamWriter(cfFile);
                Print2Txt.WriteLine("===================");
                Print2Txt.Close();
            }
            cfFile = "repoPOk.txt";
            if (!File.Exists(cfFile))
            {
                TextWriter Print2Txt = new StreamWriter(cfFile);
                Print2Txt.WriteLine("โพลเดอร์เก็บประวัติ\\");
                Print2Txt.Close();
            }
            if (File.Exists(cfFile))
            {
                string[] lines = File.ReadAllLines(cfFile);
                cfText= lines[0].Trim();
                if (Directory.Exists(cfText))
                {
                    MyGlobal.txtwrite = cfText + MyGlobal.txtwrite;
                }
            }
        }




        static void Main(string[] args)
        {
            if (File.Exists("AmpExit.txt")) { File.Delete("AmpExit.txt"); }
            PrePareVar();
            MyGlobal.cpFlag = ""; MyGlobal.cpCom = ""; MyGlobal.cpType = ""; MyGlobal.cpFileText = "";
            if (args.Length == 0) { AmpTechReadMe(); return; }
            else
            {
                if (args[0].Trim().ToUpper()=="D")
                {
                    if (!File.Exists("AmpExit.txt")) { File.Copy("Amtech.Txt", "AmpExit.txt"); }
                    return;
                }
                if (args[0].Trim().ToUpper() == "L")
                {
                    ShowFLtxt(MyGlobal.txtwrite);
                    return;
                }
                MyGlobal.cpFlag = args[0].Trim().ToUpper();
                MyGlobal.cpCom = args[1].Trim().ToUpper();
                MyGlobal.cpType = args[2].Trim();
                MyGlobal.cpFileText = args[3].Trim();
            }

            if (MyGlobal.cpFlag == "0") // RunInSource() || 
            {
                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);
            }

            // ป้องกันการเปิดโปรแกรมซ้อน
            Process mobj_pro = Process.GetCurrentProcess();
            Process[] mobj_proList = Process.GetProcessesByName(mobj_pro.ProcessName);
            if (mobj_proList.Length > 1)
            {
                Pok_Mess("รันโปรแกรมอยู่แล้ว ไม่สามารถรันโปรแกรมได้อีก");
                return;
            }

            MyGlobal.insource = 0;
            MyGlobal.in_pos_prog = 0;
            if (File.Exists(@"J:\Movie\formPOK.hav")) { MyGlobal.insource = 1; }
            if (File.Exists(@"V:\Movie\formPOK.hav")) { MyGlobal.in_pos_prog = 1; }


            if (!File.Exists(MyGlobal.txtwrite))
            {
                TextWriter WriteTxt = new StreamWriter(MyGlobal.txtwrite);
                WriteTxt.WriteLine("@เริ่มเปิดใช้โปรแกรม วัน" + DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
                WriteTxt.WriteLine("======================");
                WriteTxt.Close();
            }
            
            switch (MyGlobal.cpFlag)
            {
                case ("0"): Send_FileTxt(); break;
                case ("1"): Send_FileTxt(); break;
                case ("A"): Amphan2Com(); break;
                case ("M"): AmphanLoop(); break;
            }

        }
    }
}
