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.Diagnostics;
using System.Media;


namespace AmpTech
{
    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 = "AmpTech_" + DateTime.Now.ToString("ddMMyyyy") + ".txt";
        public static string txtReadMe = "AmpTech_Readme.txt";
        public static string cFrvBdPOS = "D:\\BdPos\\"; // ตำแหน่งของของโปรแกรม BUDDY 
    }


    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        [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 C ---> สร้างไฟล์ทดสอบ ปิดไฟ" + System.Environment.NewLine
        + "AmpTech O ---> สร้างไฟล์ทดสอบ เปิดไฟ " + 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 แทรกใน amphan.prg" + System.Environment.NewLine
        + "AmpTech M COM? n 0---> ส่งตามแบบอำพันแบบที่ n รันอิสระแบบดักจับไฟล์ txt" + System.Environment.NewLine
        + System.Environment.NewLine + System.Environment.NewLine
        + "n= 1-7 " + System.Environment.NewLine
        + "FT = ไฟล์หรือข้อความ" + System.Environment.NewLine + System.Environment.NewLine
        +"เช่น AmpTech M COM1 6 0 เป็นต้น"
        , "", 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;
        }

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


        public static void Send_FileTxt2COM_1(string cTxtFile)
        {
            if (!File.Exists(cTxtFile)) { Pok_Mess("ไม่พบไฟล์ชื่อ " + cTxtFile);return; }
            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8);
            port.Open();
            port.WriteLine(cTxtFile);
            port.Close();
        }


        public static void Send_FileTxt2COM_2(string cTxtFile)
        {
            if (!File.Exists(cTxtFile)) { Pok_Mess("ไม่พบไฟล์ชื่อ " + cTxtFile); return; }
            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8);
            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();
        }


        public static void Send_FileTxt2COM_3(string cTxtFile)
        {
            if (!File.Exists(cTxtFile)) { Pok_Mess("ไม่พบไฟล์ชื่อ " + cTxtFile); return; }
            SerialPort port = new SerialPort(MyGlobal.cpCom, 9600, Parity.None, 8);
            using (TextReader reader = File.OpenText(MyGlobal.cpFileText))
            {
               string line;
               while ((line = reader.ReadLine()) != null)
               { port.WriteLine(line);}
            }
        }


        public static void Send_FileTxt2COM_4(string cTxtFile)
        {
            if (!File.Exists(cTxtFile)) { Pok_Mess("ไม่พบไฟล์ชื่อ " + cTxtFile); return; }
        }

        public static void Send_FileTxt2COM_5(string cTxtFile)
        {
            if (!File.Exists(cTxtFile)) { Pok_Mess("ไม่พบไฟล์ชื่อ " + cTxtFile); return; }
        }


        public static void Send_FileTxt2COM_6(string cTxtFile)
        {
            if (!File.Exists(cTxtFile)) { Pok_Mess("ไม่พบไฟล์ชื่อ " + cTxtFile); return; }
            cTxtFile = cTxtFile.Trim();
            cTxtFile = cTxtFile.Substring(0, cTxtFile.Length - 4);
            string BatFile = cTxtFile + ".bat";
            if (!File.Exists(BatFile))
            {
                TextWriter WriteBAT = new StreamWriter(BatFile);
                WriteBAT.WriteLine("Mode " + MyGlobal.cpCom + " 96,n,8,1");
                WriteBAT.WriteLine("Copy " + cTxtFile + ".txt " + MyGlobal.cpCom);
                WriteBAT.WriteLine("");
                WriteBAT.WriteLine("Mode " + MyGlobal.cpCom + " 24,n,8,1");
                WriteBAT.WriteLine("Copy " + cTxtFile + ".txt " + MyGlobal.cpCom);
                WriteBAT.WriteLine("Exit");
                WriteBAT.Close();
            }
            Process.Start(BatFile);
        }


        public static void Send_FileTxt2COM_7(string cTxtFile)
        {
            if (!File.Exists(cTxtFile)) { Pok_Mess("ไม่พบไฟล์ชื่อ " + cTxtFile); return; }
            string BatFile = "Open00.bat";
            if (!File.Exists(BatFile))
            {
                TextWriter WriteBAT = new StreamWriter(BatFile);
                WriteBAT.WriteLine("Mode " + MyGlobal.cpCom + " 24,n,8,1");
                WriteBAT.WriteLine("Copy TxtAcT.Txt " + MyGlobal.cpCom);
                WriteBAT.WriteLine("");
                WriteBAT.WriteLine("Mode " + MyGlobal.cpCom + " 96,n,8,1");
                WriteBAT.WriteLine("Copy TxtAcT.Txt " + MyGlobal.cpCom);
                WriteBAT.WriteLine("Del TxtAcT.Txt");
                WriteBAT.WriteLine("Exit");
                WriteBAT.Close();
            }
            File.Copy(cTxtFile, "TxtAcT.Txt", true);
            Process.Start(BatFile);
        }


        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;
            }
        }


        public static void CopyExitFile()
        {
            File.Copy("Amtech.Txt", "AmpExit.txt",true);
        }


        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;
            }
        }


        public 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);
        }


        public static void TxtReverse(string cfFileTxt)
        {
            string cFlreverse = "Reverse.txt";
            TextWriter Print2Txt = new StreamWriter(cFlreverse);
            foreach (var line in File.ReadLines(cfFileTxt).Reverse())
            {
                Print2Txt.WriteLine(line);
            }
            Print2Txt.Close();
            ShowFLtxt(cFlreverse);
        }
             

        private static void PrePareVar()
        {
            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; }
            string cfFile, cfText;
            cfFile = "Amtech.Txt";
            if (!File.Exists(cfFile))
            {
                TextWriter Print2Txt = new StreamWriter(cfFile);
                Print2Txt.WriteLine("===================");
                Print2Txt.Close();
            }
            cfFile = "test.Txt";
            if (!File.Exists(cfFile))
            {
                TextWriter Print2Txt = new StreamWriter(cfFile);
                Print2Txt.WriteLine(":M01011");
                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;
                    MyGlobal.txtReadMe = cfText + MyGlobal.txtReadMe;
                }
            }
        }

        private static void CreateDataTest(int nRun)
        {
            string crFile,crData;
            int nCard = 6;
            if (MyGlobal.insource == 1) { nCard = 1; }
            for (int i = 1; i <=nCard ; i++)
            {
                for (int j = 1; j <= 16; j++)
                {
                    crFile="txt"+ i.ToString().Trim().PadLeft(2, '0');
                    crFile=crFile+ j.ToString().Trim().PadLeft(2, '0');
                    crFile = crFile + ".txt";
                    TextWriter Print2Txt = new StreamWriter(crFile);
                    crData = ":M"+i.ToString().Trim().PadLeft(2,'0');
                    crData = crData+ j.ToString().Trim().PadLeft(2, '0');
                    crData = crData + nRun.ToString().Trim();
                    Print2Txt.WriteLine(crData);
                    Print2Txt.Close();
                }
            }
        }


        private static bool SoftInMem(int nFlag, string cProgName) // ตรวจสอบชื่อไฟล์ 
        {
            bool lSoftInMem = false;
            Process[] proc = Process.GetProcessesByName(cProgName);
            if (proc.Length > 0)
            {
                lSoftInMem = true;
                switch (nFlag)
                {
                    case (0): break;
                }
            }
            return lSoftInMem;
        }
        /// </summary>


        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) {
                MyGlobal.cpFlag = "M"; MyGlobal.cpCom = "COM1"; MyGlobal.cpType = "0"; MyGlobal.cpFileText = "0";
                }
            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") // View Remark ไฟล์
                {
                    TxtReverse(MyGlobal.txtwrite);
                    return;
                }
                if (args[0].Trim().ToUpper() == "?") // Help 
                {
                    AmpTechReadMe();
                    return;
                }
                if (args[0].Trim().ToUpper() == "C") // สร้าง ไฟล์ ปิดไฟ
                {
                    CreateDataTest(0);
                    return;
                }
                if (args[0].Trim().ToUpper() == "O") // สร้าง ไฟล์ ปิดไฟ
                {
                    CreateDataTest(1);
                    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;
            }


            TextWriter Print2Read = new StreamWriter(MyGlobal.txtReadMe);
            Print2Read.WriteLine("cpFlag=" + MyGlobal.cpFlag);
            Print2Read.WriteLine("cpCom = " + MyGlobal.cpCom);
            Print2Read.WriteLine("cpType  =  " + MyGlobal.cpType);
            Print2Read.WriteLine("cpFileText = " + MyGlobal.cpFileText);
            Print2Read.Close();

            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"):
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                    break;
            }

        }
    }
}
