﻿using System;
using System.IO;
using System.Net;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using System.Media;
using System.Diagnostics;

// uyodupload.exe
// ทำงานแบบ Windows Application 
// ไม่จำเป็นต้องมี util.cs และ Time.cs 
namespace Original
{
    static class Program
    {
        public static string MyProg = "uyodupload".ToLower();
        public static int nForWork = 1,ntemp;
        public static string cTemp = "", cTemp2 = "";  // ตัวแปรดัมมี่
        public static bool insource = false;
        public static bool inharddisk = false;
        private static string MyApp = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        private static string MyFolderApp = System.IO.Directory.GetCurrentDirectory();  // โพลเดอร์ทำงาน
        private static string FldBakLoad = "Backup4Upload"; // สำรองการ Updown ป้องกันการโหลดซ้ำ
        private static string mCustomername = ""; // เก็บชื่อลูกค้า 
        private static string MyGoogleDrive = @"G:\My Drive\General";   // Google Drive 
        private static int nHour = 2; // เวลาในการรอ
        private static int nTimeWait = 1; // 2=Time นอกนั้นใช้ Thread.Sleep 
        public static bool runinhdonly = true; // อันนี้สำหรับ รันเครื่องที่บ้าน จะไปมองที่ R:\Temp
        private static bool lDebug = false; // สำหรับ Debug ขณะรันโปรแกรม
        // ตัวแปรเพิ่มเติ่ม
        // private static int var

        static void Readme()
        {

            TextWriter Logtxt = new StreamWriter(MyGoogleDrive +"\\"+ MyProg+"Readme.txt");
            // การใช้งาน
            Logtxt.WriteLine("*" + MyProg + ".exe  ,DT : "+ File.GetLastWriteTime(MyApp).ToString("dd/MM/yy HH:mm"));
            Logtxt.WriteLine(MyApp);
            Logtxt.WriteLine(""); 
            Logtxt.WriteLine("ชุดคำสั่ง ");
            Logtxt.WriteLine("-" + MyProg + " " + "1 --> ส่งรูปภาพ JPG ไป Line ของระบบ BdPosVFP ทุกๆ 2Hr.");
            Logtxt.WriteLine("-" + MyProg + " " + "2 --> ส่งรูปภาพ JPG ไป Line pipopyouyod");
            Logtxt.WriteLine("-" + MyProg + " " + "3 --> ส่งรูปภาพ JPG ไป Line ลูกค้าตามเวลา");
            Logtxt.WriteLine("-" + MyProg + " " + "4 --> ส่งรูปภาพ JPG ไป Line ในGoogle Drive");
            Logtxt.WriteLine("-" + MyProg + " " + "5 n --> คล้าย 4 แต่เป็นเงื่อนไข ตาม n");
            Logtxt.WriteLine("-" + MyProg + " " + "6  --> สำหรับuploadไฟล์ขึ้นHost ตั้งค่าในไฟล์ host.ini");
            Logtxt.WriteLine("     อัพไฟล์ตามค่าใน fileupload.txt");
            Logtxt.WriteLine("-" + MyProg + " " + "A Folder HD,Folder HOST --> Upload ไฟล์ทังFolder");
            Logtxt.WriteLine("-" + MyProg + " " + "7 n --> คล้าย 6 แต่ส่งเป็นข้อความ");
            Logtxt.WriteLine("-" + MyProg + " " + "8  --> สำหรับDownloadไฟล์ขึ้นHost ตั้งค่าในไฟล์ host.ini");
            Logtxt.WriteLine("     อัพไฟล์ตามค่าใน fileupload.txt");
            Logtxt.WriteLine("-" + MyProg + " " + "9 n --> คล้าย 8 แต่ส่งเป็นข้อความ");
            Logtxt.WriteLine("-" + MyProg + " " + "L Folder --> แสดงไฟล์บนโพลเดอร์");
            Logtxt.WriteLine(""); Logtxt.WriteLine("");
            // ไฟล์ช่วยงานต่างๆ
            Logtxt.WriteLine("repoway.txt");
            Logtxt.WriteLine(ReadREPOway(0));
            Logtxt.WriteLine("CPREPDAILY : " + ReadREPOway(1));
            Logtxt.WriteLine("CPREPREPO  : " + ReadREPOway(2));
            Logtxt.WriteLine("CPCLOUD    : " + ReadREPOway(3));
            Logtxt.WriteLine("CPCLOUDBAK : " + ReadREPOway(4));
            Logtxt.WriteLine("CPCLOUDTXT : " + ReadREPOway(5));
            Logtxt.WriteLine("CPCLOUDPDF : " + ReadREPOway(6));
            Logtxt.WriteLine("CPSCREENLO : " + ReadREPOway(7));
            Logtxt.WriteLine("CLINETOKEN : " + ReadREPOway(8));
            Logtxt.WriteLine(""); Logtxt.WriteLine("");
            if (File.Exists(@"D:\Temp\SaveJPGtoLineTime.txt"))
            {
                Logtxt.WriteLine("D:\\Temp\\TempJPG.jpg DT : " + File.GetLastWriteTime(@"D:\Temp\SaveJPGtoLineTime.txt").ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }
            string[] readText;

            if (File.Exists(MyFolderApp + "\\uyodupload.ini"))
            {
                Logtxt.WriteLine("uyodupload.ini ,DT : " + File.GetLastWriteTime(MyFolderApp + "\\uyodupload.ini").ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(MyFolderApp + "\\uyodupload.ini");
                readText = File.ReadAllLines(MyFolderApp + "\\uyodupload.ini");
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            if (Directory.Exists(ReadREPOway(7)))
            {
                DirectoryInfo dFolderList = new DirectoryInfo(ReadREPOway(7));
                FileInfo[] FileList = dFolderList.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
                Logtxt.WriteLine("ไฟล์รูปภาพในคลาวด์");
                foreach (FileInfo cFileList in FileList)
                {
                    Logtxt.WriteLine(cFileList.FullName + " DT : " + File.GetLastWriteTime(cFileList.FullName).ToString("dd/MM/yy HH:mm"));
                }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = MyGoogleDrive + "\\FileInGoogleDrive.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("-FileInGoogleDrive.txt ,DT : " + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp);
                Logtxt.WriteLine("เก็บ ID ไฟล์ใน Google Cloud ");
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = MyGoogleDrive + "\\FileInGoogleDIV.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("FileInGoogleDIV.txt ,DT : " + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp);
                Logtxt.WriteLine("เก็บ ID ไฟล์ใน Google Cloud ตามเงื่อนไข");
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); }  }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "host.ini";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("-"+MyFolderApp+"\\host.ini ,DT : " + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp);
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "fileupload.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("-" + MyFolderApp + "\\fileupload.txt ,DT : " + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp);
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "fileuploadstatus.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("-" + MyFolderApp + "\\fileuploadstatus.txt ,DT : " + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp);
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            Logtxt.Close();Logtxt.Dispose();
            if (Layout.Program.Password.Input_Password("Open Readme.txt","")) { Util.Program.OpenWebSite(MyGoogleDrive + "\\" + MyProg + "Readme.txt"); }

        }


        static void Information()
        {
            Util.Program.Pok_Mess("Adjust Pc's Environment" + T(1)+"For Complete");
        }


        static string T(int nOption)  // ใช้แทนประโยคที่ยาวๆ  มีในโปรแกรมหลักและ Util.cs
        {
            string cT="";
            switch (nOption)
            {
                case (1): cT = Environment.NewLine;  break;
                case (2): cT = Environment.NewLine+Environment.NewLine; break;
                case (3): cT = Environment.NewLine + Environment.NewLine + Environment.NewLine; break;
            }
            return cT;
         } 



        static void FTPandLine(string uFullFileName, string uFileName,int nOption)  
        {
            //Create FTP request
            string ftpAdd = "ftp://ftp.youyod.com/public_html/uyod_member";
            string username = "administratorforower@youyod.com"; string password = "โฮสต์พิภพอยู่ยอด";
            if (MyTime.Program.h(0,username) == "ok")  
            {
                ftpAdd = MyTime.Program.h(1, "")+ "/uyod_member";
                username = MyTime.Program.h(2, "");
                password = MyTime.Program.h(3, "");
            }
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpAdd + "/" + uFileName);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = true;
            //Load the file
            FileStream stream = File.OpenRead(uFullFileName);
            byte[] buffer = new byte[stream.Length];
            try
            {
                stream.Read(buffer, 0, buffer.Length);
                stream.Close();
                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
                request = null;
                // สำเร็จส่งไปที่ Line ต่อ  repoway.txt
                switch (nOption)
                {
                    case (2): cTemp = "ru2ldVzxl3ZR92gaCvDLERGab4RzHH23N1qZHaRnWxx"; break; // Line id Pipopyouyod
                    default: cTemp = ReadREPOway(8); mCustomername = ""; break; // เป็น LineToken ของลูกค้า 
                }
                if (cTemp != "") // ส่งรูปไปที่ Line 
                {
                    Util.Program.Pok_Process("util_Pok2", "2 " + cTemp +" "+ mCustomername+DateTime.Now.ToString("dd/MM/yy HH:mm") + "+0 + 0+http://uyod.net/uyod_member/" + uFileName);
                }
                Util.Program.Pok_InHarddisk("ส่งไฟล์ "+uFullFileName+T(1)+"ไป "+ ftpAdd + "/" + uFileName+T(1)+"สำเร็จ");  
            }
            catch (Exception e)
            {
                stream.Close();
                if (inharddisk == true) { MessageBox.Show(e.Message + T(1) + e.ToString()+"ส่งรูปไม่ได้"); }
                // ส่งแบบไม่ต้องส่งรูปแทน 
                Util.Program.Pok_Process("util_Pok2", "2 " + cTemp + " " + mCustomername + DateTime.Now.ToString("dd/MM/yy HH:mm") +"#มีปัญหาในการส่งรูป");
            }
            cTemp = "";
        }

        // static String
        static string ReadREPOway(int nLine)
        {
            string cfRepoway=MyFolderApp+@"\repoway.txt", cTextRet; ;
            if (!File.Exists(cfRepoway)) { cfRepoway = @"D:\BdPosVFP\repoway.txt"; }
            if (!File.Exists(cfRepoway)) { return ""; }
            // 1=CPREPDAILY,2=CPREPREPO,3=CPCLOUD,4=CPCLOUDBAK,5=CPCLOUDTXT
            // 6=CPCLOUDPDF,7=CPSCREENLO,8=CLINETOKEN
            string[] lines = File.ReadAllLines(cfRepoway);
            // เพิ่มโพลเดอร์ General
            if (lines[3].Trim() != "" && Directory.Exists(lines[3].Trim()) && !Directory.Exists(lines[3].Trim()+"General") )
            { Directory.CreateDirectory(lines[3].Trim() + "General"); }
            if (nLine == 0) { cTextRet=cfRepoway; } else { cTextRet= lines[nLine].Trim(); }
            return cTextRet;
        }

        static String CustomerTxt()
        {
            if (!File.Exists("customer.txt")) { return ""; }
            string[] lines = File.ReadAllLines("customer.txt");
            return lines[0].Trim();
        }

        // ส่งรูปจาก ระบบ BUDDY ไปที่ Line  
        static void BuddySendJPGtoLine()
        {
            if (Directory.Exists(ReadREPOway(7)))
            {
                DirectoryInfo dFolderList = new DirectoryInfo(ReadREPOway(7));
                FileInfo[] FileList = dFolderList.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
                int iActive=0;
                foreach (FileInfo cFileList in FileList)
                {
                    if (CompFileTime(nHour * 60, cFileList.FullName.Trim(), cFileList.Name.Trim()))  // nHour ชั่วโมง จาก uyodupload.ini
                    {
                        FTPandLine(cFileList.FullName.Trim(), cFileList.Name.Trim(),1); 
                        if (iActive > 0) { MyTime.Program.Pok_TimeWait(1, 2); }  // 2 วินาที 
                        iActive++;
                    }
                    else { Util.Program.Pok_InHarddisk("ยังไม่ครบเวลา "+nHour.ToString()+" ชั่วโมง" ); }
                }
            }
        }


        static bool CompFileTime(int nWarning,string FLESouce, string FLETarget) // เปรียบเทียบไฟล์และCopy ห่างกัน nWarning นาที
        {
            bool lCompareFile = false;
            if (!Directory.Exists(MyFolderApp+"\\Temp")) { Directory.CreateDirectory(MyFolderApp+"\\Temp"); } // Temp จะอยู่ใกล้ D:\\BdPosVFP
            FLETarget = MyFolderApp+"\\Temp\\" + FLETarget;
            if (!File.Exists(FLESouce)) { return lCompareFile; }
            if (File.Exists(FLESouce) && !File.Exists(FLETarget)) { lCompareFile=true; } // ไม่เจอไฟล์ให้ทำงานเลย 
            else
            {
                TimeSpan ts = (File.GetLastWriteTime(FLESouce) - File.GetLastWriteTime(FLETarget)  );
                if (ts.Minutes > nWarning) { lCompareFile = true; }
            }
            if (lCompareFile==true) { File.Copy(FLESouce, FLETarget, true); }
            return lCompareFile;
        }

        // Save เป็นรูปและเก็บไฟล์ ส่งไปที่ Line 
        static void SaveJPGtoLine(int nOption)
        {
            if (!File.Exists("UtilPok3.exe")) { return; }
            Util.Program.Pok_Process("UtilPok3","1 D:\\Temp TempJPG");
            MyTime.Program.Pok_TimeWait(1, 2); // 2 วินาที
            if (File.Exists(@"D:\Temp\TempJPG.jpg"))
            {
                FTPandLine(@"D:\Temp\TempJPG.jpg", "TempJPG.jpg",nOption);
                MyTime.Program.Pok_TimeWait(1, 4); // 4 วินาที
                File.Delete(@"D:\Temp\TempJPG.jpg");
            }
        }

        // Save เป็นรูปและเก็บไฟล์ ส่งไปที่ Line แบบดูเวลา 
        static void SaveJPGtoLineTime()
        {
            string FileCookies = @"D:\Temp\SaveJPGtoLineTime.txt";  // สร้างไฟล์เพื่อจับเวลา 
            if (!File.Exists(FileCookies)) { SaveJPGtoLine(1); Util.Program.SaveCookies(FileCookies); }
            else  // ทำงานหลัก 
            {
                FileInfo fi = new FileInfo(FileCookies);
                if (Util.Program.bTStime(3, fi.LastWriteTime,nHour))
                { SaveJPGtoLine(1); Util.Program.SaveCookies(FileCookies); }
            }
        }

        // เรียกไฟล์รูปจาก Google Drive ไปไลน์
        static void CallJPG_Gdv2Line() 
        {
            HistorySendLine(1, "");
            string FileCookies = @"D:\Temp\SaveJPGtoLineTime.txt";  // สร้างไฟล์เพื่อจับเวลา 
            if (!File.Exists(FileCookies)) { CallJPG_Gdv2Line2(); Util.Program.SaveCookies(FileCookies); }
            else {
                FileInfo fi = new FileInfo(FileCookies);
                 if (Util.Program.bTStime(3, fi.LastWriteTime, nHour)) { CallJPG_Gdv2Line2(); Util.Program.SaveCookies(FileCookies); }
            }
        }

        static void CallJPG_Gdv2Line2() 
        {
            string txtCommand;
            txtCommand = "1 " +(char)34+MyGoogleDrive+(char)34  + " ScreenActive";
            if (Directory.Exists(MyGoogleDrive)) { Util.Program.Pok_Process("utilpok3", txtCommand); }
            MyTime.Program.Pok_TimeWait(1, 2); // 2 วินาที
            // สร้างไฟล์ txt เพื่อเก็บใน Google 
            cTemp = MyGoogleDrive+"\\FileInGoogleDrive.txt";
            if (!File.Exists(cTemp))
            {
                TextWriter Write2Txt = new StreamWriter(cTemp);
                Write2Txt.WriteLine("** ต้องเปิดใน Share เป็นEdit ได้และCopy เฉพาะลิงค์");
                Write2Txt.WriteLine("** util_Pok2 2 9s2uTS8ibhTC4dNpJEmM6FM3Qh7HKUGRcxpYi7CvkZn TestPicture+0+0+https://drive.google.com/uc?id=");
                Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine("");
                Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine("");
                Write2Txt.Close();Write2Txt.Dispose();
            }
            string[] readText = File.ReadAllLines(cTemp);
            foreach (string GFleName in readText)
            {
                // รูปแบบที่เก็บไว้ใน ไฟล์ Text
                cTemp2 = GFleName.Trim();
                if (cTemp2 != "")
                {
                    if (cTemp2.Substring(0, 1) != "*")
                    {
                        txtCommand = " 2 " + ReadREPOway(8) + " " + DateTime.Now.ToString("dd/MM/yy,HH:mm");
                        txtCommand = txtCommand + "+0+0+https://drive.google.com/uc?id=" + cTemp2;
                        Util.Program.Pok_Process("util_Pok2", txtCommand);
                        HistorySendLine(2, "util_Pok2 " + txtCommand);
                        Util.Program.Pok_InHarddisk(txtCommand);
                    }
                } // ทำงานส่งไฟล์ไปไลน์
            }
            cTemp = "";cTemp2 = "";
        }

        // เรียกไฟล์รูปจาก Google Drive ไปไลน์ แต่ตามเงื่อนไข 
        static void CallJPGGdrvDiv(string cOption) // จะต่างๆจาก ตรงรูปแบบ n,Id รูป
        {
            HistorySendLine(1, "");
            string txtCommand;
            txtCommand = "1 " + (char)34 + MyGoogleDrive + (char)34 + " ScreenActive";
            if (Directory.Exists(MyGoogleDrive)) { Util.Program.Pok_Process("utilpok3", txtCommand); }
            MyTime.Program.Pok_TimeWait(1, 2); // 2 วินาที
            // สร้างไฟล์ txt เพื่อเก็บใน Google 
            cTemp = MyGoogleDrive + "\\FileInGoogleDIV.txt";
            if (!File.Exists(cTemp))
            {
                TextWriter Write2Txt = new StreamWriter(cTemp);
                Write2Txt.WriteLine("** รูปแบบ 1,ชื่อลิงค์ เช่น 00,id....................");
                Write2Txt.WriteLine("** ต้องเปิดใน Share เป็นEdit ได้และCopy เฉพาะลิงค์");
                Write2Txt.WriteLine("** util_Pok2 2 9s2uTS8ibhTC4dNpJEmM6FM3Qh7HKUGRcxpYi7CvkZn TestPicture+0+0+https://drive.google.com/uc?id=");
                Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine("");
                Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine("");
                Write2Txt.Close(); Write2Txt.Dispose();
            }
            string[] readText = File.ReadAllLines(cTemp);
            foreach (string GFleName in readText)
            {
                // รูปแบบที่เก็บไว้ใน ไฟล์ Text
                cTemp2 = GFleName.Trim();  // ตำแหน่งที่ 01, เป็นเงื่อนไข ตั้งแต่ 3 เป็น ไอดี รูป nn,id...................... 
                if (cTemp2 != "")
                {
                    if (cTemp2.Substring(0, 1)!="*" && cTemp2.Substring(0, 2) == cOption)
                    {
                        txtCommand = " 2 " + ReadREPOway(8) + " " + DateTime.Now.ToString("dd/MM/yy,HH:mm");
                        txtCommand = txtCommand + "+0+0+https://drive.google.com/uc?id=" + cTemp2.Substring(3);
                        Util.Program.Pok_Process("util_Pok2", txtCommand);
                        HistorySendLine(2, "util_Pok2 "+txtCommand);
                    }
                } // ทำงานส่งไฟล์ไปไลน์
            }
            cTemp = ""; cTemp2 = "";
        }

        static void HistorySendLine(int nOption,string cMessage) 
        {
            string FleHistory = MyGoogleDrive + "\\History2Line.txt";
            if (nOption == 1 || !File.Exists(FleHistory))
            {
                TextWriter Write2Txt = new StreamWriter(FleHistory);
                Write2Txt.WriteLine(DateTime.Now.ToString("dd/MM/yyyy HH: mm:ss"));
                Write2Txt.WriteLine("** Line Token uyod@hotmail.com 	eGt9R1toYxIlcWORG0mdCoDrhSXHzvV0k0SUkqdTmQ4 (BdPosVFP Login)");
                Write2Txt.Close();Write2Txt.Dispose();
            }
            if (nOption==2)
            {
                using (StreamWriter FleAddText = File.AppendText(FleHistory))
                {
                    FleAddText.WriteLine(cMessage);
                    FleAddText.Close();
                }
            }
        }

        static void ListFileFromHost(string cFolder)
        {
            // เปลี่ยนตำแหน่งเพื่อทำงานที่บ้านได้ง่ายขึ้น
            if (!insource && inharddisk && runinhdonly) { Directory.SetCurrentDirectory(@"R:\Temp"); }  
            if (!File.Exists("host.ini")) { Util.Program.Pok_Mess("ให้ Run uyodupload 6 เพื่ออ่าน host.ini");    return; }
            string[] hostconfig = File.ReadAllLines("host.ini");
            string host = hostconfig[0].Trim(); 
            string user = hostconfig[1].Trim();
            string password = hostconfig[2].Trim();
            if (MyTime.Program.h(0,user) == "ok")  
            {
                host = MyTime.Program.h(1, "");
                user = MyTime.Program.h(2, "");
                password = MyTime.Program.h(3, "");
            }
            string folderonhost;
            if (cFolder == "0") { folderonhost = host; } else { folderonhost = host + "/" + cFolder; }
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderonhost);
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(user, password);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                string names = reader.ReadToEnd();  
                TextWriter WriteTxt = new StreamWriter("hostlistfile.txt");
                WriteTxt.WriteLine("Folder "+folderonhost  +"  ," + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                WriteTxt.WriteLine("");
                WriteTxt.WriteLine(names);
                WriteTxt.Close();
                WriteTxt.Dispose();
                reader.Close();
                response.Close();
                Layout.Program.LayOut.ScreenShow(6, "แสดงไฟล์ในโพลเดอร์", cFolder, "สำเร็จ", "เปิดไฟล์ hostlistfile.txt", "");
            }
            catch (Exception e)
            {  Layout.Program.LayOut.ScreenShow(7, "Error :", "ไม่พบโพลเดอร์", folderonhost,e.ToString() , "");  }
        }


        static void Cr_hostinit() // สร้างไฟล์ host.ini
        {
            if (!File.Exists("host.ini"))
            {
                TextWriter hostini = new StreamWriter("host.ini");
                hostini.WriteLine("ftp://ftp.youyod.com/public_html");
                hostini.WriteLine("administratorforower@youyod.com");
                hostini.WriteLine("โฮสต์พิภพอยู่ยอด");
                hostini.WriteLine(""); hostini.WriteLine(""); hostini.WriteLine(""); hostini.WriteLine("");
                hostini.WriteLine("Host ,User ,password");
                hostini.Close(); hostini.Dispose();
            }
        }


        static void LoadFiletoHost(int nload,int noption,string txtoption)  // ส่งขึ้น Host  
        {
            // nload=1 Upload 2=Download 
            // noption=1 อ่านไฟล์จาก fileupload.txt ,2=ไฟล์1ไฟล์ ,3=ทั้งโพลเดอร์ ,4=ส่งไฟล์เท็กมา
            string p = "LoadFiletoHost";
            if (lDebug) {Special.DEBUG.D(p, " -00 p="+p);}

            // **** เปลี่ยนตำแหน่งเพื่อทำงานที่บ้านได้ง่ายขึ้น
            if (!insource && inharddisk && runinhdonly) { Directory.SetCurrentDirectory(@"R:\Temp"); }
            Directory.SetCurrentDirectory(@"R:\Temp");
            TextWriter crmsg = new StreamWriter("fileuploadstatus.txt"); // เก็บประวัติการ Upload 
            Cr_hostinit();  // สร้างไฟล์ host.ini
            if (lDebug) { Special.DEBUG.D(p, " -01 fileuploadstatus.txt"); }
            string[] filelist;
            int nWarning = 0;
            string cWord,folderinhd ,fileInhd, folderonhost, fileonhost, fullfileonhost,webonhost;
            TextWriter fileupload;
            if (lDebug) { Special.DEBUG.D(p, " -02 "); }
            switch (noption)
            {
                case (2):  // อ่านจากไฟล์เฉพาะ แค่ไฟล์เดียว  
                    if (lDebug) { Special.DEBUG.D(p, " -03 tmfileupload.txt"); }
                    fileupload = new StreamWriter("tmfileupload.txt");
                    fileupload.WriteLine(txtoption);
                    fileupload.Close(); fileupload.Dispose();
                    filelist = File.ReadAllLines("tmfileupload.txt");
                    crmsg.WriteLine("อ่านจากไฟล์ tmfileupload.txt");
                    break;
                case (4): // รับค่าเป็นไฟล์ Text   
                    if (lDebug) { Special.DEBUG.D(p, " -04 txtoption="+ txtoption); }
                    filelist = File.ReadAllLines(txtoption);
                    crmsg.WriteLine("อ่านจากไฟล์ "+txtoption);
                    break;
                case (3): // Up ทั้งโพลเดอร์   
                    cWord = txtoption.Trim();  // @"R:\Temp,temp" พารามิเตอร์ จะส่ง โพลเดอร์ของ HD และ HOST 
                    if (lDebug) { Special.DEBUG.D(p, " -05 cWord="+ cWord); }
                    int index = cWord.IndexOf(",");
                    if (index < 0) { folderinhd = cWord; folderonhost = ""; }
                    else { folderinhd = cWord.Substring(0, index); folderonhost = cWord.Substring(index + 1); }
                    if (folderonhost == "") { folderonhost = "0"; }
                    if (!Directory.Exists(folderinhd)) { Util.Program.Pok_Mess("ไม่พบโพลเดอร์ " + folderinhd); return; }
                    fileupload = new StreamWriter("allfileupload.txt");
                    DirectoryInfo listfile = new DirectoryInfo(folderinhd);
                    FileInfo[] listfilerun = listfile.GetFiles("*.*", SearchOption.TopDirectoryOnly);
                    foreach (FileInfo alllistfile in listfilerun)
                    { fileupload.WriteLine("0,"+alllistfile.FullName.Trim()+","+folderonhost+","+alllistfile.Name.Trim()); }
                    fileupload.Close(); fileupload.Dispose();
                    filelist = File.ReadAllLines("allfileupload.txt");
                    crmsg.WriteLine("อ่านจากไฟล์ allfileupload.txt");
                    break;
                default:
                    if (!File.Exists("fileupload.txt"))  { 
                        fileupload = new StreamWriter("fileupload.txt");
                        fileupload.WriteLine("* หมายเหตุ 0=ไม่เตือน 1=เตือน 2=แสดงเวบ ,ไฟล์   ,โพลเดอร์ในHost 0=Root  ,ชื่อไฟล์ในHost");
                        fileupload.WriteLine(@"** เช่น 1,V:\_My Cloud\G Drive\Internet\youyod.html,0,youyod.html");
                        fileupload.WriteLine("*xn.vidioactive.forme.love");
                        fileupload.WriteLine(""); fileupload.WriteLine(""); fileupload.WriteLine(""); fileupload.WriteLine("");
                        fileupload.WriteLine(""); fileupload.WriteLine(""); fileupload.WriteLine(""); fileupload.WriteLine("");
                        fileupload.Close(); fileupload.Dispose();
                    }
                    filelist = File.ReadAllLines("fileupload.txt");
                    crmsg.WriteLine("อ่านจากไฟล์ fileupload.txt");
                    if (lDebug) { Special.DEBUG.D(p, " -06 fileupload.txt"); }
                    break;
            }
            string[] hostconfig = File.ReadAllLines("host.ini"); 
            string host = hostconfig[0].Trim();
            string user = hostconfig[1].Trim();
            string password = hostconfig[2].Trim();
            if (lDebug) { Special.DEBUG.D(p, " -07 host=" + host+" ,user="+user+" ,pass="+password); }
            if (MyTime.Program.h(0,user) == "ok")  
            {
                host = MyTime.Program.h(1, "");
                user = MyTime.Program.h(2, "");
                password = MyTime.Program.h(3, "");
            }
            crmsg.WriteLine("host = " + host +T(1)+"user = " + user +T(1)+"password = "+password+T(2));
            string txtloadstatus="",allfilesend="", allfoldersend = "";
            int nerror = 0;
            if (lDebug) { Special.DEBUG.D(p, " -08 -Before foreach"); }
            foreach (string cfilelist in filelist) 
            {
                cWord = cfilelist.Trim();
                if (cWord != "" && cWord.Substring(0,1)!="*")
                {
                    if (lDebug) { Special.DEBUG.D(p, " -09 cWord="+ cWord); }
                    nWarning = 0;  fileInhd = ""; folderonhost = ""; fileonhost = "";

                    if (lDebug) { Special.DEBUG.D(p, " -091"); }


                    cuttext2host(cWord,ref nWarning,ref fileInhd,ref folderonhost,ref fileonhost);

                    if (lDebug) { Special.DEBUG.D(p, " -092"); }

                    // กรณีไม่ส่งชื่อไฟล์มา 
                    if (fileInhd != "" && fileonhost == "") { fileonhost = fileInhd; Util.Program.splitFDandFL(ref cTemp, ref fileonhost); cTemp = ""; }
                    fullfileonhost = host; if (folderonhost == "0") { folderonhost = ""; } else { fullfileonhost = fullfileonhost + "/" + folderonhost; } 
                    fullfileonhost = fullfileonhost + "/" + fileonhost;
                    if (lDebug) { Special.DEBUG.D(p, " -093 fullfileonhost=" + fullfileonhost); }
                    // หาชื่อเวบใน https://
                    int windex;
                    webonhost = host.Trim();
                    windex = webonhost.IndexOf("ftp.");
                    if (windex > 0) { webonhost = "https://"+webonhost.Substring(windex+4); }
                    windex = webonhost.IndexOf("public_html");   
                    if (windex > 0) { webonhost = webonhost.Substring(0, windex); }
                    if (folderonhost != "") { webonhost = webonhost + folderonhost + "/"; }
                    webonhost = webonhost + fileonhost;
                    allfilesend = allfilesend.Trim() +","+ fileonhost.Trim();

                    if (lDebug) { Special.DEBUG.D(p, " -094 webonhost="+ webonhost); }

                    if (folderonhost == "") { allfoldersend = allfoldersend.Trim() + ",root"; }
                    else { allfoldersend = allfoldersend.Trim() + "," + folderonhost; }
                    ntemp = 0;
                    // กรณี Upload ให้ดูไฟล์ต้นทางและปลายทาง
                    if (nload==1) { if (File.Exists(fileInhd) && fileonhost != "") { ntemp = 1; }    }
                    // กรณี Upload ให้ดูไฟล์ปลายทาง
                    if (nload == 2) { if (fileonhost != "") { ntemp = 1; } }

                    if (lDebug) { Special.DEBUG.D(p, " -095 fileInhd="+ fileInhd); }

                    if (ntemp==1)
                    {
                        FtpWebRequest request;
                        switch (nload)
                        {
                            case (1):  // สำหรับ Upload 
                                if (lDebug) { Special.DEBUG.D(p, " -10 สำหรับ Upload "); }
                                txtloadstatus = " Upload ไป ";
                                request = (FtpWebRequest)FtpWebRequest.Create(fullfileonhost);  
                                request.Method = WebRequestMethods.Ftp.UploadFile;
                                request.Credentials = new NetworkCredential(user, password);
                                request.UsePassive = true;
                                request.UseBinary = true;
                                request.KeepAlive = true;
                                FileStream stream = File.OpenRead(fileInhd);
                                byte[] buffer = new byte[stream.Length]; 
                                try
                                {
                                    stream.Read(buffer, 0, buffer.Length);
                                    stream.Close();
                                    Stream reqStream = request.GetRequestStream();
                                    reqStream.Write(buffer, 0, buffer.Length);
                                    reqStream.Close();
                                    request = null;
                                    switch (nWarning)
                                    {
                                        case (1): // เตือน  
                                            Layout.Program.LayOut.ScreenShow(6, "ส่งไฟล์", fileInhd, txtloadstatus + fullfileonhost, "สำเร็จ", "");
                                            break;
                                        case (2): // แสดงหน้าเวบ  
                                            Util.Program.OpenWebSite(webonhost);
                                            break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    nerror = 1;
                                    stream.Close();
                                    if (nWarning == 1)  {
                                        Layout.Program.LayOut.ScreenShow(7, "Error :", fileInhd, txtloadstatus + fullfileonhost, "ไม่สำเร็จ", "");
                                        Util.Program.Pok_InHarddisk(ex.Message); }
                                        crmsg.WriteLine(fileInhd + txtloadstatus + fullfileonhost + " เกิดข้อผิดพลาด ,"+ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                                }
                                // สิ้นสุด Upload 
                                // ตรวจสอบว่าเป็นไฟล์ php หรือไม่ ให้ upload เป็น txt อีกครั้ง
                                if (fileInhd.Substring(fileInhd.Length - 4).ToLower() == ".php") { php2txtupload(fileInhd, fullfileonhost+".txt"); } 
                                break;
                            case (2):  // สำหรับ Download   
                                if (lDebug) { Special.DEBUG.D(p, " -11 สำหรับ Download   "); }
                                txtloadstatus = " Download มาที่ ";
                                try  {
                                    request = (FtpWebRequest)WebRequest.Create(fullfileonhost);
                                    request.Method = WebRequestMethods.Ftp.DownloadFile;
                                    request.Credentials = new NetworkCredential(user, password);
                                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                                    Stream ftpStream = response.GetResponseStream();
                                    using (Stream fileStream = File.Create(fileInhd)) {  ftpStream.CopyTo(fileStream);  }
                                    ftpStream.Close();
                                    request = null;
                                    if (nWarning == 1) { Layout.Program.LayOut.ScreenShow(6, "รับไฟล์", fullfileonhost, txtloadstatus + fileInhd , "สำเร็จ", ""); }
                                    crmsg.WriteLine(fullfileonhost  + txtloadstatus + fileInhd + " สำเร็จ ,"+ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                                }
                                catch (Exception ex) {
                                    request = null;
                                    nerror = 1;
                                    if (nWarning == 1) {
                                        Layout.Program.LayOut.ScreenShow(7, "Error :", fullfileonhost, txtloadstatus + fileInhd , "ไม่สำเร็จ", "");
                                        Util.Program.Pok_InHarddisk(ex.Message); }
                                    crmsg.WriteLine(fullfileonhost + txtloadstatus + fileInhd + " เกิดข้อผิดพลาด ," + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                                }
                                // สิ้นสุด Upload 
                                break;
                        } // Swicth (nload)
                    }
                   else {
                        if (lDebug) { Special.DEBUG.D(p, " -12"); }
                        if (nWarning == 1)
                        { Layout.Program.LayOut.ScreenShow(7, "ไม่พบไฟล์ ", fileInhd, " เป็นช่องว่าง " + fullfileonhost, "ไม่สำเร็จ", "ลองตรวจสอบ"); }
                        crmsg.WriteLine(fileInhd + "-->" + fullfileonhost + " ไม่สำเร็จ ,"+ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    }
                }
            } // foreach
            if (allfilesend!="") {allfilesend=allfilesend.Substring(1);}
            if (lDebug) { Special.DEBUG.D(p, " -13 allfilesend="+ allfilesend); }
            if (allfoldersend != "") { allfoldersend = allfoldersend.Substring(1); }
            if (nWarning == 0 && inharddisk)
            { if (nerror == 0) { Layout.Program.LayOut.ScreenShow(6, allfilesend, "  ===>"+txtloadstatus, allfoldersend  , "แล้ว", ""); }
                else { Layout.Program.LayOut.ScreenShow(7, allfilesend, txtloadstatus, allfoldersend, "ไม่สำเร็จ", ""); }
            }            
			crmsg.Close(); crmsg.Dispose();
            if (File.Exists("tmfileupload.txt")) { File.Delete("tmfileupload.txt"); }
            if (lDebug) { Special.DEBUG.D(p, " -99 -Finnish"); }
        }

        // ตรวจสอบว่าเป็นไฟล์ php หรือไม่ ให้ upload เป็น txt อีกครั้ง
        static void php2txtupload(string fileInhd,string fullfileonhost)  
        {
            FtpWebRequest request;
            request = (FtpWebRequest)FtpWebRequest.Create(fullfileonhost); 
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("pipop@uyod.net", "u13421342");
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = true;
            FileStream stream = File.OpenRead(fileInhd);
            byte[] buffer = new byte[stream.Length];
            try
            {
                stream.Read(buffer, 0, buffer.Length);
                stream.Close();
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
                request = null;
            }
            catch (Exception ex) {  stream.Close();      }
            // สิ้นสุด Upload 
        }


        static void cuttext2host(string cWord, ref int nWarning,ref string fileInhd,ref string folderonhost, ref string fileonhost)
        {
            cWord = cWord.Trim() ;
            int index; string cMinute;
            index = 0; nWarning = 0; fileInhd = ""; folderonhost = ""; fileonhost = "";
            index = cWord.IndexOf(','); 
            try {
                if (index > 0)
                { // 1
                    cMinute = cWord.Substring(0, index).Trim();
                    nWarning = int.Parse(cMinute);
                    cWord = cWord.Substring(index + 1).Trim();
                    index = cWord.IndexOf(',');
                    if (index > 0)
                    { // 2
                        fileInhd = cWord.Substring(0, index).Trim();
                        cWord = cWord.Substring(index + 1).Trim();
                        index = cWord.IndexOf(',');
                        if (index > 0)
                        { // 3
                            folderonhost = cWord.Substring(0, index).Trim();
                            fileonhost = cWord.Substring(index + 1).Trim();
                        } //3
                    } // 2
                } //1
            }
            catch(Exception e) { Util.Program.Pok_Mess("ข้อความมีปัญหา ตรวจสอบข้อมูลด้วยครับ"+T(2)+e.ToString());   return; }
        }


        static void Init()
        {
            if (!Directory.Exists(FldBakLoad)) { Directory.CreateDirectory(FldBakLoad); }
            if (!Directory.Exists("History")) { Directory.CreateDirectory("History"); }
            if (!Directory.Exists(@"D:")) { return; }
            if (!Directory.Exists(@"D:\BdPosVFP")) { Directory.CreateDirectory(@"D:\BdPosVFP"); }
            if (!Directory.Exists(@"D:\Temp")) { Directory.CreateDirectory(@"D:\Temp"); }
            if (Directory.Exists(@"G:\My Drive") && !Directory.Exists(@"G:\My Drive\General"))
            { Directory.CreateDirectory(@"G:\My Drive\General"); }
            // Copy จาก BdPos ไป BdPosVFP
            if (Directory.Exists(@"D:\BdPos"))
            {
                DirectoryInfo dFolderList = new DirectoryInfo(@"D:\BdPos");
                FileInfo[] FileList = dFolderList.GetFiles("u*.exe", SearchOption.TopDirectoryOnly);
                foreach (FileInfo cFileList in FileList)
                {
                    if (cFileList.Name.ToLower() != "uyodload.exe" && !File.Exists(@"D:\BdPosVFP\" + cFileList.Name))
                    { File.Copy(cFileList.FullName, @"D:\BdPosVFP\" + cFileList.Name); }
                }
            }
            if (!File.Exists(MyFolderApp + "\\uyodupload.ini"))
            {
                TextWriter List2Write = new StreamWriter(MyFolderApp + "\\uyodupload.ini");
                List2Write.WriteLine("2        ตั้งเวลา Save รูปไปไลน์ หน่วยเป็นชั่วโมง");
                List2Write.WriteLine("1        1=Thread.Sleep,2=Timer");
                List2Write.WriteLine("");
                List2Write.WriteLine("");
                List2Write.WriteLine("");
                List2Write.WriteLine("");
                List2Write.WriteLine("");
                List2Write.Close(); List2Write.Dispose();
            }
            // ตรวจสอบหาโพลเดอร์ Gdrive ที่มี  
            if (!Directory.Exists(MyGoogleDrive)) // เช็คใน Drive G ก่อน
            {
                MyGoogleDrive = @"E:\_Cloud\General"; if (!Directory.Exists(MyGoogleDrive)) // เช็คใน Drive E 
                {
                    MyGoogleDrive = ReadREPOway(3) + "General"; if (!Directory.Exists(MyGoogleDrive)) // เช็คใน repoway.txt
                    { MyGoogleDrive = MyFolderApp; }
                }
            }
            Cr_hostinit();
            string[] lines = File.ReadAllLines(MyFolderApp + "\\uyodupload.ini");
            try { nHour = int.Parse(lines[0].Substring(0, 3)); }
            catch { nHour = 2; Util.Program.Pok_Mess("uyodupload.ini บรรทัดที่ 1" + T(1) + "3 หลักแรกต้องตั้งเป็นตัวเลขเท่านั้นและไม่มี ."); }
            try { nTimeWait = int.Parse(lines[1].Substring(0, 2)); } catch { nTimeWait = 1; }
        }


        static void LoadFiletoCard()
        {
            if (Util.Program.ExpirUsedDT("fileuploadtocard.exp",30))    { return; } // เช็ดวันหมดอายุ
            string subfld = "demo"; 
            cTemp = "fileuploadtocard.ini";
            if (File.Exists(cTemp))
            {
                string[] lines = File.ReadAllLines(cTemp);
                subfld = lines[0].Trim();
            }
            cTemp = "fileuploadtocard.txt"; 
            if (!File.Exists(cTemp))
            {
                TextWriter Logtxt = new StreamWriter(cTemp);
                if (Util.Program.CompareFileAndCopy("letter.txt",FldBakLoad+ "\\letter.txt"))
                { Logtxt.WriteLine("0," + MyFolderApp + "\\letter.txt,card/"+subfld+","); }
                if (Util.Program.CompareFileAndCopy("state.txt", FldBakLoad + "\\state.txt"))
                { Logtxt.WriteLine("0," + MyFolderApp + "\\state.txt,card/" + subfld + ","); }
                if (Util.Program.CompareFileAndCopy("picture.txt", FldBakLoad + "\\picture.txt"))
                { Logtxt.WriteLine("0," + MyFolderApp + "\\picture.txt,card/" + subfld + ","); }
                if (Util.Program.CompareFileAndCopy("detail.txt", FldBakLoad + "\\detail.txt"))
                { Logtxt.WriteLine("0," + MyFolderApp + "\\detail.txt,card/" + subfld + ","); }
                Logtxt.WriteLine("0,"+MyFolderApp+ "\\money.txt,card,");
                Logtxt.WriteLine("0,"+MyFolderApp+ "\\people.jpg,card/" + subfld + ",");
                Logtxt.Close(); Logtxt.Dispose();
            }
            LoadFiletoHost(1, 4,"fileuploadtocard.txt"); // Upload ทั้ง Folder   
            if (File.Exists("people.jpg")) { File.Delete("people.jpg"); } // ทำงานเสร็จให้ลบไฟล์รูปด้วย เพราะมีขนาดใหญ่
            if (File.Exists("money.txt")) { File.Delete("money.txt"); } // ทำงานเสร็จให้ลบไฟล์รูปด้วย 
            if (Util.Program.Pok_YesNOW("ตอบ Yes เพื่อดูเวบไซค์ ")) { Util.Program.OpenWebSite("http://uyod.net/card/"+subfld);  }
            cTemp = ""; cTemp2 = "";
        }


        static void LoadFiletoRent()  
        {
            string subfld = "demo"; 
            cTemp = "fileuploadtorent.ini";
            if (File.Exists(cTemp)) {
                string[] lines = File.ReadAllLines(cTemp);
                subfld=lines[0].Trim();
            }
            // เช็ดวันหมดอายุ
            if (subfld=="demo" && Util.Program.ExpirUsedDT("fileuploadtorent.exp", 15)) { return; }
            cTemp = "fileuploadtorent.txt";
            TextWriter Logtxt;
            Logtxt = new StreamWriter(cTemp);
            for (int i=1; i<=25; i++)
            {
                switch (i)
                {
                    case (21): cTemp2 = "company.txt"; break;
                    case (22): cTemp2 = "header.txt"; break;
                    case (23): cTemp2 = "bank.txt"; break;
                    case (24): cTemp2 = "logo.jpg"; break;
                    case (25): cTemp2 = "qrcode.jpg"; break;
                    default:  cTemp2 = i.ToString().Trim().PadLeft(2,'0')+".txt";  break;
              }
                if (Util.Program.CompareFileAndCopy(cTemp2,FldBakLoad+"\\"+cTemp2))
                {Logtxt.WriteLine("0," + MyFolderApp + "\\" + cTemp2 + ",rent/" + subfld + ","); }
            }
            Logtxt.Close(); Logtxt.Dispose();
            LoadFiletoHost(1, 4, "fileuploadtorent.txt");  
            // ทำงานเสร็จให้ลบไฟล์รูปด้วย เพราะมีขนาดใหญ่
            if (File.Exists("logo.jpg")) { File.Delete("logo.jpg"); }
            if (File.Exists("qrcode.jpg")) { File.Delete("qrcode.jpg"); }
            if (Util.Program.Pok_YesNOW("ตอบ Yes เพื่อดูเวบไซค์  rent.uyod.net/"+subfld)) { Util.Program.OpenWebSite("http://rent.uyod.net/"+subfld); }
            cTemp = ""; cTemp2 = "";
        }


        // ใช้สำหรับ rent.uyod.net กรณีเริ่มเดือนใหม่
        static void LoadFiletoRentCut()  
        {
            if (!Layout.Program.Password.Input_Password("ต้องการเริ่มต้น ข้อมูลเดือนใหม่", "1234"))
            { Util.Program.Pok_Mess("ยกเลิก");  return; }

            string cDTbackup = "Backup\\"+DateTime.Now.ToString("ddMMyyyy")+"\\",cfDTbackup;
            if (!Directory.Exists("Backup")) { Directory.CreateDirectory("Backup"); }
            if (!Directory.Exists(cDTbackup)) { Directory.CreateDirectory(cDTbackup); }
            cfDTbackup = cDTbackup + "header.txt";
            if (!File.Exists(cfDTbackup)) { File.Copy("header.txt", cfDTbackup); }
            else { Util.Program.Pok_Mess("วันนี้หัวข้อนี้ทำไม่ได้แล้วครับ "+T(2)+"เนื่องจากทำไปแล้ว" +T(2) + "ให้ทำใหม่วันพรุ่งนี้"); return; }
            string[] readText;  string cText; int nPosi ; TextWriter FleSave;
            for (int i = 1; i <= 20; i++)
            {
                cTemp = i.ToString().Trim().PadLeft(2, '0') + ".txt";
                cfDTbackup = cDTbackup + cTemp;
                if (File.Exists(cTemp))
                {
                    File.Copy(cTemp, cfDTbackup,true);
                    readText = File.ReadAllLines(cTemp);
                    FleSave = new StreamWriter(cTemp);
                    string cText1, cText2;
                    foreach (string s in readText)
                    {
                        cText = s.Trim(); cText1 = ""; cText2="";
                         nPosi = cText.IndexOf("#");
                        // หาครั้งแรก 
                        if (nPosi != -1)  {
                            cText1 =cText.Substring(0, nPosi).Trim();
                            cText2 = cText.Substring(nPosi+1).Trim();
                            // หาครั้งสอง
                            nPosi = cText2.IndexOf("#");
                            if (nPosi != -1)
                            {
                                if (cText2.Substring(0, 1) == "#") { cText2 = ""; }
                                else { cText2 = cText2.Substring(0, nPosi); }
                            }
                            cText = cText1.Trim() +"#"+ cText2.Trim()+"##";
                        }
                        FleSave.WriteLine(cText);
                    }
                    FleSave.Close();FleSave.Dispose();
                }
            }
            cTemp= "";
        }

        // สำหรับรอการอัพโหลดขึ้น HOST รันตลอดเวลา 
        public static void DoWhileUpload()
        {
            string[] readText;
            string fle4history = "History\\History4DoWhile.txt";
            if (File.Exists(fle4history)) {
                readText = File.ReadAllLines(fle4history);
                ntemp = readText.Length;
                if (ntemp > 2) { File.Delete(fle4history); }
            }
            if (!File.Exists(fle4history))
            {
                TextWriter Historytxt = new StreamWriter(fle4history);
                Historytxt.WriteLine("สร้าง @" + DateTime.Now.ToString("dd/MM/yy HH:mm"));
                Historytxt.Close(); Historytxt.Dispose();
            }
            string drv = "";
            cTemp = "DoWhileUpload.dir";
            if (!File.Exists(cTemp)) {
                TextWriter Write2Txt = new StreamWriter(cTemp);
                Write2Txt.WriteLine("Folder Action");
                Write2Txt.WriteLine(""); Write2Txt.WriteLine(""); Write2Txt.WriteLine("");
                Write2Txt.Close();Write2Txt.Dispose();
            }
            string[] fldlist = File.ReadAllLines(cTemp);
            DirectoryInfo dFolderList; FileInfo[] FolderList; string cEx,cFileChk;
            TextWriter Logtxt = new StreamWriter("DoWhileUpload.txt");
            StreamWriter Logtxt2 = File.AppendText(fle4history);  // ต่อไฟล์ 
            foreach (string fld in fldlist) {
                if (fld != "") { drv = fld.Trim();
                    if (Directory.Exists(drv))
                    {
                        dFolderList = new DirectoryInfo(drv);
                        FolderList = dFolderList.GetFiles("*.*", SearchOption.TopDirectoryOnly);
                        foreach (FileInfo cFileList in FolderList)
                        {
                            cEx= cFileList.Extension.ToLower();
                            if (cEx==".txt" || cEx == ".pdf" || cEx == ".jpg") // เฉพาะไฟล์ 3 นามสกุล
                            {
                                cFileChk =FldBakLoad+"\\"+cFileList.Name;
                                // ทำการเทียบไฟล์  ให้ Copy เฉพาะไฟล์ใหม่ 
                                if (Util.Program.CompareFileAndCopy(cFileList.FullName,cFileChk))
                                {
                                    if (inharddisk) { Logtxt.WriteLine("0," + cFileList.FullName.Trim() + ",temp,"); }
                                    else { Logtxt.WriteLine("0," + cFileList.FullName.Trim() + ",uyodteam,"); }
                                    Logtxt2.WriteLine(cFileList.FullName.Trim() + " ==> " + DateTime.Now.ToString("dd/MM/yy HH:mm:ss"));
                                }
                            }
                        }
                    } else { Util.Program.Pok_Mess("ไม่พบโพลเดอร์ " + drv + T(2) + "ตรวจสอบโพลเดอร์ใน DoWhileUpload.dir" + T(2) + "ดูครับ"); }
                }
            }
            Logtxt.Close(); Logtxt.Dispose();
            Logtxt2.Close(); Logtxt2.Dispose();
            readText = File.ReadAllLines("DoWhileUpload.txt"); 
            ntemp = readText.Length;
            if (ntemp>0) { // มีไฟล์อัพโหลดให้ทำงาน
                LoadFiletoHost(1, 4, "DoWhileUpload.txt");
                Util.Program.ReverseTextFile("History\\History4DoWhile.txt", "History\\History4DoWhileR.txt",100);
                if (File.Exists("C:\\Windows\\Media\\Speech On.wav"))
                { SoundPlayer POKSound = new SoundPlayer("C:\\Windows\\Media\\Speech On.wav"); POKSound.Play(); }
            }
            cTemp = ""; cTemp2 = ""; ntemp = 0;
        }


        static void Test_Prog()  
        {
            // ListFileFromHost("customer");
            // Readme();
            // LoadFiletoHost(1,1,"");
            // LoadFiletoHost(2, 1, "");
            // LoadFiletoHost(1, 3, @"R:\_Cloud\AM\Txt,demo/am");
            // Layout.Program.LayOut.ScreenShow(6,"A","B","C","D","E"); //  แสดงปรกติ 
            // Layout.Program.LayOut.ScreenShow(7, "A", "B", "C", "D", "E"); // แสดง Error
            // if (Util.Program.Pok_YesNOW("ddddd")) { Util.Program.Pok_Mess("OK"); } else { Util.Program.Pok_Mess("Cancel"); }
            // if (Layout.Program.LayOut.)) { Util.Program.Pok_Mess("OK"); } else { Util.Program.Pok_Mess("Cancel"); }
            // if (Layout.Program.Password.Input_Password("ต้องการเริ่มต้น ข้อมูลเดือนใหม่","1234"))
            // { Util.Program.Pok_Mess("OK"); }
            // else { Util.Program.Pok_Mess("Cancel"); }
        }


        static void Main(string[] args)
        {
            if (MyApp.Substring(0,2)=="V:") { insource = true; } // Run กับ Source
            if (Directory.Exists(@"R:\Temp")) {inharddisk=true;}  // Run กับ Harddisk   
            lDebug = Special.DEBUG.Cr_Debug(MyProg);
            string p = "Main";
            if (lDebug) {Special.DEBUG.D(p, " -01 -insource="+insource);}
            string cpFlag,cpFlag2="00";
            if (args.Length == 0) {
                // กรณีไม่ส่งค่า พารามิเตอร์
                if (insource)
                { cpFlag = "T";  //  cpFlag = "T";   pipopU T เป็นการทดสอบ
                  if (lDebug) { Special.DEBUG.D(p, " -02 -cpFlag="+cpFlag);}
                } 
                else {
                    if (lDebug) { Special.DEBUG.D(p, " -03 -cpFlag2="+cpFlag2); }
                    // ปรับค่าตามชื่อไฟล์ได้
                    if (File.Exists("card.hav")) { Util.Program.Pok_InHarddisk("พบไฟล์ card.hav"); cpFlag = "C"; }
                    else {
                        if (File.Exists("rent.hav")) { Util.Program.Pok_InHarddisk("พบไฟล์ rent.hav"); cpFlag = "R"; }
                        else {
                            if (File.Exists("dowhileupload.hav")) { Util.Program.Pok_InHarddisk("พบไฟล์ dowhileupload.hav"); cpFlag = "W"; }
                            else { Information(); return; }
                        }
                    }
                }
            }  
            else { cpFlag = args[0].Trim();
                if (cpFlag == "5" || cpFlag == "7" || cpFlag == "9" || cpFlag == "A" || cpFlag == "L")
                { cpFlag2 = args[1].Trim(); if (cpFlag2 == "") { Util.Program.Pok_Mess("ระบุ พารามิเตอร์ ไม่ครบ"); return; }  }
            }
            if (lDebug) { Special.DEBUG.D(p, " -04"); }
            nForWork =1;  
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); // เปลี่ยนรูปแบบวันที่ เป็น GB
            mCustomername = CustomerTxt();
            Init();
            if (cpFlag=="1" || cpFlag == "2" || cpFlag == "3" || cpFlag == "4" || cpFlag == "5")
            {   if (!Directory.Exists(@"D:\")) { Util.Program.Pok_InHarddisk("ไม่พบ Drive D:" + T(2) + "ทำงานต่อไม่ได้"); return; }
                Directory.SetCurrentDirectory(@"D:\BdPosVFP");
            } // ใช้เป็นโพลเดอร์หลักในการทำงาน  
            if (lDebug) { Special.DEBUG.D(p, " -041"); }
            switch (cpFlag) 
            {
                case ("0"): 
                case ("?"): Readme(); break;  
                case ("T"): Test_Prog();    break;
                case ("1"): BuddySendJPGtoLine(); break;  // ส่งรูปจาก ระบบ uyod.net  ไปที่ Line  
                case ("2"): SaveJPGtoLine(2); break; // Save และส่งไป Line 
                case ("3"): SaveJPGtoLineTime(); break; // Save และส่งไป Line แบบจับเวลา
                case ("4"): CallJPG_Gdv2Line(); break; // ส่งรูปภาพ JPG ไป Line ในGoogle Drive ตามไฟล์ FileInGoogleDrive.txt ทั้งหมด 
                case ("5"): CallJPGGdrvDiv(cpFlag2);  break; // ส่งรูปภาพ JPG ไป Line ในGoogle Drive ตามไฟล์ FileInGoogleDIV.txt ทั้งหมด 
                case ("6"): LoadFiletoHost(1,1,""); if (lDebug) { Special.DEBUG.D(p, " -051 -LoadFiletoHost()"); } break; // Upload To Host 
                case ("7"): LoadFiletoHost(1,2,cpFlag2); break; // Upload To Host 
                case ("8"): LoadFiletoHost(2, 1, ""); break; // Download To Host  
                case ("9"): LoadFiletoHost(2, 2, cpFlag2); break; // Download To Host 
                case ("A"): LoadFiletoHost(1, 3, cpFlag2); break; // Upload ทั้ง Folder   
                case ("C"): runinhdonly = false; LoadFiletoCard(); break; // ส่งเข้าเวบ uyod.net/card 
                case ("R"): runinhdonly = false; LoadFiletoRent(); break; // ส่งเข้าเวบ uyod.net/rent/??? 
                case ("RC"): runinhdonly = false; LoadFiletoRentCut(); break; // ตัดไฟล์ก่อนอัพโหลด
                case ("L"): ListFileFromHost(cpFlag2);  break; // แสดงชื่อไฟล์
                case ("W"):  // สำหรับรอการอัพโหลดขึ้น HOST รันตลอดเวลา 
                    TextWriter Logtxt = new StreamWriter("WTimewait.txt");
                    Logtxt.WriteLine("โปรแกรมกำลังทำงาน ... สำหรับ Upload ไฟล์ขึ้นเวบ");
                    Logtxt.WriteLine("เริ่มใช้เวลา "+DateTime.Now.ToString("dd/MM/yy HH:mm"));
                    Logtxt.WriteLine("ไฟล์เก็บประวัติทำงาน History4DoWhileR.txt");
                    Logtxt.WriteLine("พัฒนาเวบไซท์โดย youyod.com");
                    Logtxt.Write(MyFolderApp + @"\History\DoWhileUploadR.html");
                    Logtxt.Close();Logtxt.Dispose();
                    runinhdonly = false;
                    // ตรวจสอบเปิดซ้ำ 
                    Process mobj_pro = Process.GetCurrentProcess();
                    Process[] mobj_proList = Process.GetProcessesByName(mobj_pro.ProcessName);
                    if (mobj_proList.Length > 1) { Util.Program.Pok_InHarddisk("เปิดโปรแกรมซ้ำ"); return; }
                    Application.EnableVisualStyles();
                    Application.Run(new Layout.WTimewait());
                    break; 
                default:  break;  
            }
            if (lDebug) { Special.DEBUG.D(p, " -99 -Finnish"); }
        }
}
}
