using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;


namespace Util_pok2
{
    static class Program
    {
        public class MyGlobal
        {
            public static int insource = 0;
            public static string cpFlag, cpWord1, cpWord2;
            public static string cpText1, cpText2;  // ชุดคำที่ 1,2 เป็นต้นไป
            public static string cpMessage; // เหมือน  
            public static string cpLatitude, cpLongtitude;  // ชุดคำที่ 1,2 เป็นต้นไป
        }

        private static void UtilPOK2ReadMe() // Pipop
        {
            MessageBox.Show(
              "util_pok2 1 T M  --->Line Notify  M=* ขึ้นบรรทัดใหม่  (util_pok 5)" + System.Environment.NewLine
            + "util_pok2 2 T M+0+0+Picture (util_pok 6)" + System.Environment.NewLine
            + "             --->Line Notify Token ข้อความ+stickerPackageID+stickerID+Picture"+System.Environment.NewLine
            + "             เช่น util_pok 6 Token Pipop*Youyod+0+0+http://uyod.net/logo.jpg" + System.Environment.NewLine
            + "             เช่น util_pok 6 Token Pipop*Youyod+0+0+" + System.Environment.NewLine
            + "util_pok2 3 0 0  --->สภาพแวดล้อมของวินโดร์ util_pok 7" + System.Environment.NewLine
            + "util_pok2 4 0 0  --->32 หรือ 64 บิต (w32.bit,w64.bit) util_pok 8" + System.Environment.NewLine
            );
        }

        static void Pok_Mess(string cfWord)
        {
            if (MyGlobal.insource==0) { return; }
            MessageBox.Show(cfWord + System.Environment.NewLine
            + "" + System.Environment.NewLine
            + "" + System.Environment.NewLine
            , "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        private static void SetupVar()
        {
            if (System.IO.Directory.Exists(@"J:\Entertain\Movie\Private")) { MyGlobal.insource = 1; }
        }



        static void OpenWebSite(String URLname)
        {
            var opentwebthis = new ProcessStartInfo("chrome.exe");  // iexplore.exe
            opentwebthis.Arguments = URLname;
            Process.Start(opentwebthis);
        }


        private static void LineNotify(string cToKen,string LineMessage)  
        {
            LineMessage = Text2Replace(LineMessage);
            if (MyGlobal.insource == 1)
            {
                Pok_Mess("ข้อความเตือนทางไลน์ " + System.Environment.NewLine + System.Environment.NewLine
                   + "ToKen : " + cToKen + System.Environment.NewLine + ",Message : " + LineMessage);
            }
            if (cToKen=="")
            { Pok_Mess("LineNotify Error: ค่า Token เป็นช่องว่าง");
                OpenWebSite("https://notify-bot.line.me/my/");
                return;
            } 
            if (LineMessage == "") {Pok_Mess("LineNotify Error: ข้อความ เป็นช่องว่าง");  return; }

            var request = (HttpWebRequest)WebRequest.Create("https://notify-api.line.me/api/notify");
            var postData = string.Format("message={0}",LineMessage);
            var data = Encoding.UTF8.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.Headers.Add("Authorization", "Bearer " + cToKen);

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

        // เปลี่ยน * เป็น ขึ้นบรรทัดใหม่  Pipop
        private static string Text2Replace(string mText) 
        {
            string cWordTake, cWordFor;
            mText = mText.Trim();
            cWordFor = "";
            for (int i = 0; i < mText.Length; i++)
            {
                cWordTake = mText.Substring(i, 1);
                switch (cWordTake)
                {
                    case ("*"):
                        cWordFor = cWordFor + System.Environment.NewLine; break;
                    default:
                        cWordFor = cWordFor + cWordTake; break;
                }
            }
            return cWordFor;
        }


        private static void WinVironment()
        {
            // Check Public IP
            string url = "http://checkip.dyndns.org";
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);
            System.Net.WebResponse resp = req.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            string response = sr.ReadToEnd().Trim();
            string[] a = response.Split(':');
            string a2 = a[1].Substring(1);
            string[] a3 = a2.Split('<');
            string ipGlobal = a3[0];

            TextWriter WriteTxt = new StreamWriter("Environment.txt");
            WriteTxt.WriteLine("Username     : {0}", Environment.UserName);
            WriteTxt.WriteLine("Computername : {0}", Environment.MachineName);
            WriteTxt.WriteLine("Domain       : {0}", Environment.UserDomainName);
            WriteTxt.WriteLine("Directory    : {0}", Environment.CurrentDirectory);
            WriteTxt.WriteLine("OS(64BIT)    : {0}", Environment.Is64BitOperatingSystem);
            WriteTxt.WriteLine("Machine      : {0}", Environment.MachineName);
            WriteTxt.WriteLine("OS           : {0}", Environment.OSVersion);
            WriteTxt.WriteLine("Public IP    : {0}", ipGlobal);
            if (MyGlobal.cpWord1=="1") // หาละติจูด,ลองติจูดด้วย
            {
                MyGlobal.cpLatitude = "?"; MyGlobal.cpLongtitude = "?";
                WriteTxt.WriteLine("");
                WriteTxt.WriteLine("");
                WriteTxt.WriteLine("");
            }
            else
            {
                WriteTxt.WriteLine("");
                WriteTxt.WriteLine("");
                WriteTxt.WriteLine("");
            }
            WriteTxt.Close();
        }

        private static void LineNotify2(string cToKen,string cLineWordSet)
        {
            string LineMessage = "";
            int stickerPackageID = 0;
            int stickerID = 0;
            string pictureUrl = "";
            // แยกคำจาก LineMessage
            string cWordTake, cWordFor;
            cLineWordSet = cLineWordSet.Trim();
            cWordFor = "";
            int j = 0;
            for (int i = 0; i < cLineWordSet.Length; i++)
            {
                cWordTake = cLineWordSet.Substring(i, 1);
                switch (cWordTake)
                {
                    case ("+"):
                        j++;
                        switch (j)
                        {
                            case (1): LineMessage = cWordFor; break;
                            case (2): stickerPackageID = int.Parse(cWordFor)  ; break;  
                            case (3): stickerID = int.Parse(cWordFor); break;
                        }
                        cWordFor = "";
                        break;
                    case ("*"):
                        cWordFor = cWordFor + System.Environment.NewLine; break;
                    default:
                        cWordFor = cWordFor + cWordTake; break;
                }
            }
            //
            pictureUrl = cWordFor;// อันสุดท้าย

            LineMessage = Text2Replace(LineMessage);
            if (MyGlobal.insource == 1)
            {
                Pok_Mess("ข้อความเตือนทางไลน์ " + System.Environment.NewLine + System.Environment.NewLine
                +"cToKen :" + cToKen + System.Environment.NewLine
                + ",LineMessage :" + LineMessage + System.Environment.NewLine
                + ",stickerPackageID :" + stickerPackageID.ToString() + System.Environment.NewLine
                + ",stickerID :" + stickerID.ToString() + System.Environment.NewLine
                + ",pictureUrl :" + pictureUrl);
            }
            if (cToKen == "")
            {
                Pok_Mess("LineNotify Error: ค่า Token เป็นช่องว่าง");
                OpenWebSite("https://notify-bot.line.me/my/");
                return;
            }
            try
            {
                var request = (HttpWebRequest)WebRequest.Create("https://notify-api.line.me/api/notify");
                var postData = string.Format("message={0}", LineMessage);
                if (stickerPackageID > 0 && stickerID > 0)
                {
                    var stickerPackageId = string.Format("stickerPackageId={0}", stickerPackageID);
                    var stickerId = string.Format("stickerId={0}", stickerID);
                    postData += "&" + stickerPackageId.ToString() + "&" + stickerId.ToString();
                }
                if (pictureUrl != "")
                {
                    var imageThumbnail = string.Format("imageThumbnail={0}", pictureUrl);
                    var imageFullsize = string.Format("imageFullsize={0}", pictureUrl);
                    postData += "&" + imageThumbnail.ToString() + "&" + imageFullsize.ToString();
                }
                var data = Encoding.UTF8.GetBytes(postData);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                request.Headers.Add("Authorization", "Bearer " + cToKen);
                using (var stream = request.GetRequestStream()) stream.Write(data, 0, data.Length);
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception ex)
            {
                Pok_Mess("ส่งข้อความไลน์ไมได้ "+ex.ToString());
            }
        }


        private static void Win32Or64BIT()
        {
            if (!System.IO.File.Exists("Dummy.txt"))
            {
                TextWriter WriteTxt = new StreamWriter("Dummy.txt");
                WriteTxt.WriteLine("32or64");
                WriteTxt.Close();
            }
            if (Environment.Is64BitOperatingSystem) // เป็นวินโดร์ 64 บิต 
            {
                if (!System.IO.File.Exists("w64.bit")) { System.IO.File.Copy("Dummy.txt","w64.bit"); }
                if (System.IO.File.Exists("w32.bit")) { System.IO.File.Delete("w32.bit"); }
            }
            else // เป็นวินโดร์ 32 บิต 
            {
                if (!System.IO.File.Exists("w32.bit")) { System.IO.File.Copy("Dummy.txt", "w32.bit"); }
                if (System.IO.File.Exists("w64.bit")) { System.IO.File.Delete("w64.bit"); }
            }
        }


        private static void TestPOK()
        {



        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            MyGlobal.cpFlag = ""; MyGlobal.cpWord1 = ""; MyGlobal.cpWord2 = "";
            MyGlobal.cpText1 = ""; MyGlobal.cpText2 = "";MyGlobal.cpMessage = "";
            if (args.Length == 0) { UtilPOK2ReadMe(); return; } 
            else
            {
                MyGlobal.cpFlag = args[0];
                for (int i = 1; i < args.Length; i++)
                { MyGlobal.cpText1 = MyGlobal.cpText1 + " " + args[i]; }
                for (int i = 2; i < args.Length; i++)
                {
                    MyGlobal.cpText2 = MyGlobal.cpText2 + " " + args[i];
                    MyGlobal.cpMessage = MyGlobal.cpMessage+System.Environment.NewLine+args[i];
                }
            }
            MyGlobal.cpFlag = MyGlobal.cpFlag.Trim().ToUpper();
            MyGlobal.cpText1 = MyGlobal.cpText1.Trim();
            MyGlobal.cpText2 = MyGlobal.cpText2.Trim();
            MyGlobal.cpMessage = MyGlobal.cpMessage.Trim();

            if (MyGlobal.cpText1.Length != 0) { MyGlobal.cpWord1 = args[1].Trim(); }
            if (MyGlobal.cpText2.Length != 0) { MyGlobal.cpWord2 = args[2].Trim(); }
            if (MyGlobal.cpMessage.Length != 0)
            { MyGlobal.cpMessage=System.Environment.NewLine +MyGlobal.cpMessage; }

            SetupVar();
            if (MyGlobal.insource==1)
            {
                Pok_Mess("cpFlag=" + MyGlobal.cpFlag
                    + System.Environment.NewLine + System.Environment.NewLine
                    + ",cpWord1=" + MyGlobal.cpWord1 + ",cpWord2=" + MyGlobal.cpWord2
                    + System.Environment.NewLine + System.Environment.NewLine
                    + ",cpText1=" + MyGlobal.cpText1 + ",cpText2=" + MyGlobal.cpText2);
             }
            switch (MyGlobal.cpFlag)
            {
                case ("T"): TestPOK(); break; 
                case ("?"): UtilPOK2ReadMe(); break;
                case ("1"): LineNotify(MyGlobal.cpWord1, MyGlobal.cpText2); break;
                case ("2"): LineNotify2(MyGlobal.cpWord1, MyGlobal.cpText2); break;  // Pipop
                case ("3"): WinVironment(); break; // สภาพแวดล้อมวินโดร์
                case ("4"): Win32Or64BIT(); break; // ตรวจว่าเป็น 32 หรือ 64 BIT
            }
       }
   }
}
