using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.Http;
using System.Numerics;
using System.Globalization;
using System.Collections.Specialized;
using System.Net.Http;
using System.Net.Http.Headers;

namespace WDT_Project
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SemaphoreSlim semaphore;
        SemaphoreSlim limitlamp;
        /// <summary>
        /// 
        /// </summary>
        static SemaphoreSlim semaphore_test = new SemaphoreSlim(500);
        /// <summary>
        /// 
        /// </summary>
        private System.Windows.Forms.FolderBrowserDialog FolderBrowserDialog;
        /// <summary>
        /// 
        /// </summary>
        private System.Windows.Forms.OpenFileDialog OpenFileDialog;
        /// <summary>
        /// 
        /// </summary>
        private Line_Notify line_Notify;
        /// <summary>
        /// 
        /// </summary>
        //private string pathfileSignal = @"D:/patlog_auto2023_04_25.csv";
        //private string pathfileSignal = @"C:\PATLITE SIGNAL OUTPUT\2023-10-04.csv";
        private string pathfileSignal = @"\\192.168.0.200\ftp_server\plc1\2023-10-05.csv";
        /// <summary>
        /// 
        /// </summary>
        private string pathfileSignalCopy = "";
        /// <summary>
        /// 
        /// </summary>
        private string folderDistination = "";
        /// <summary>
        /// 
        /// </summary>
        private bool TaskRunning { get; set; }
        /// <summary>
        /// 
        /// </summary>
        private string[] strlistData { get; set; }
        /// <summary>
        /// 
        /// </summary>
        private int concurrent = 5;
        /// <summary>
        /// 
        /// </summary>
        private string url = "https://tom-demo-01.proen.app.ruk-com.cloud/wd-oms/pegasus/Ratchet-websockets/oms-app/post.php";
        //private string url = "https://tom-demo-01.proen.app.ruk-com.cloud/wd-oms/pegasus/Ratchet-websockets/oms-app/wdt-clients2.php";

        /// <summary>
        /// 
        /// </summary>
        private bool initailCompelte { get; set; }
        /// <summary>
        /// 
        /// </summary>
        private bool _fristInitail { get; set; }
        /// <summary>
        /// 
        /// </summary>
        private bool ValueConfrim { get; set; }
        /// <summary>
        /// 
        /// </summary>
        private bool LineAlart { get; set; }
        /// <summary>
        /// 
        /// </summary>
        Inifile _config = new Inifile();
        /// <summary>
        /// 
        /// </summary>
        Log _log;
        /// <summary>
        /// 
        /// </summary>
        private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
        /// <summary>
        /// 
        /// </summary>
        private int[] lamp = new int[6];
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            initailCompelte = false;
            ///
            initialConfig();
            ///
            this.FolderBrowserDialog = new FolderBrowserDialog();
            ///
            disable_textbox();
            ///
            _log = new Log(GetPath_Logfile());
            ///
            backgroundWorker1.WorkerSupportsCancellation = true;
            ///
            semaphore = new SemaphoreSlim(concurrent);
            ///
            limitlamp = new SemaphoreSlim(5);
            ///
            line_Notify = new Line_Notify();
            ///
            btnSelectPath.Enabled = false;
            ///
            txtState_toPHP.ReadOnly = true; txtState_toPHP.Cursor = Cursors.Arrow;
            ///
            txtResponse.ReadOnly = true; txtResponse.Cursor = Cursors.Arrow;
            ///
            txtLog_Exception.ReadOnly = true; txtLog_Exception.Cursor = Cursors.Arrow;
            ///
            tss_statusTask.Text = "Stop...";
            ///
            _fristInitail = true;
            ///
            //string _pathFolder = @"C:\PATLITE SIGNAL OUTPUT";
            ///
            //string[] dirs = Directory.GetFiles(_pathFolder, "*.csv");
            ///
            //pathfileSignal = dirs[dirs.Length - 1];
            ///
            //_config.IniWriteValue("LogReader", "pathCSVfile", pathfileSignal);
            ///
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            ///
            this.OpenFileDialog = new System.Windows.Forms.OpenFileDialog();
            //Icon appIcon = Icon.ExtractAssociatedIcon(GetPath_Icon());
            //// Check if icon is null or not
            //if (appIcon != null)
            //{
            //    // Save the icon or do something else with it..
            //    appIcon.ToBitmap().Save("D:\\icon.ico");
            //}
            //Properties.Settings.
            AssignID_Machine();

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
            string version = fvi.FileVersion;

            this.Text = "WDT-FileSignalReader V" + version;

        }
        private void initialConfig()
        {
            try
            {
                _config.INIPath = GetPathFile();
                folderDistination = _config.IniReadValue("LogReader", "pathfileSignal");
                url = _config.IniReadValue("LogReader", "url");
                concurrent = int.Parse(_config.IniReadValue("LogReader", "concurrent"));
                pathfileSignal = _config.IniReadValue("LogReader", "pathCSVfile");
                Line_Notify.pathPicture = _config.IniReadValue("LogReader", "pathPicture");
                Line_Notify.destinationPath = _config.IniReadValue("LogReader", "pathPictureLog");

                btnSelectPathParameter.Enabled = false;
                initailCompelte = true;
                Valueto_Textbox();
                disable_textbox();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Initial Config file Error", "Initail Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ///
                txtPathFile.Enabled = false;
                ///
                txtPathFile.Text = "";
                ///
                initailCompelte = false;
                ///
                btnEditSave.Text = "Save";
            }
        }
        bool statusGropA = false;
        bool statusGropB = false;
        async Task PostDataAsync(string[] listData)
        {
            await semaphore.WaitAsync();
            ///
            try
            {
                var httpClient = new HttpClient();
                ///
                var requestContent_signal = new FormUrlEncodedContent(new Dictionary<string, string>{
                { "insert_timestamp",           listData[0].Replace("\"","") },
                { "ieee_address",               listData[1].Replace("\"","") },
                { "red_information",            listData[2].Replace("\"","") },
                { "amber_information",          listData[3].Replace("\"","") },
                { "green_information",          listData[4].Replace("\"","") },
                { "blue_information",           listData[5].Replace("\"","") },
                { "white_information",          listData[6].Replace("\"","") },
                { "buzzer_information",         listData[7].Replace("\"","") },
                { "wdt_monitoring_information", listData[8].Replace("\"","") },});
                ///
                var response_signal = await httpClient.PostAsync(url, requestContent_signal);
                ///
                var responseContent_signal = await response_signal.Content.ReadAsStringAsync();
                ///
                _config.IniWriteValue("cache", listData[1].Replace("\"", ""), listData[0].Replace("\"","")); //Record to caghe file
                ///
                Console.WriteLine(responseContent_signal);
                ///
                reponse_state(responseContent_signal);
            }
            finally
            {
                semaphore.Release();
            }
        }
        async Task PostCounterAsync(string[] listData)
        {
            await semaphore.WaitAsync();
            ///
            //_config.IniWriteValue("cache", listData[1], listData[0]); //Record to caghe file
            ///
            try
            {
                var httpClient = new HttpClient();
                ///
                var requestContent = new FormUrlEncodedContent(new Dictionary<string, string>{
                { "timestamp",           listData[0] },
                { "ieee_address",               listData[1] },
                { "count_val",                  listData[13] },});
                ///
                var response = await httpClient.PostAsync(url, requestContent);
                ///
                var responseContent = await response.Content.ReadAsStringAsync();
                ///
                Console.WriteLine(responseContent);
                ///
                reponse_state(responseContent);
            }
            finally
            {
                semaphore.Release();
            }
        }
        private Task Signal_toLamp(string s_Red, string s_Blue, string s_Green, string s_Orange, string s_White, string Buzzer)
        {
            lamp[0] = int.Parse(s_Red);
            lamp[1] = int.Parse(s_Blue);
            lamp[2] = int.Parse(s_Green);
            lamp[3] = int.Parse(s_Orange);
            lamp[4] = int.Parse(s_White);
            lamp[5] = int.Parse(Buzzer);
            ///
            return Task.CompletedTask;
        }
             

        private async Task UpdateLamp()
        {
            try
            {
                await limitlamp.WaitAsync();
                ///
                await On_Lamp();
                ///
                await Off_Lamp();
            }
            catch
            {

            }
            finally
            {
                limitlamp.Release();
            }
        }
        private Task On_Lamp()
        {
            if (lamp[0] == 1) { lamp_Red.BackColor = Color.Red; }
            if (lamp[1] == 1) { lamp_Blue.BackColor = Color.DodgerBlue; }
            if (lamp[2] == 1) { lamp_Green.BackColor = Color.Lime; }
            if (lamp[3] == 1) { lamp_Orange.BackColor = Color.DarkOrange; }
            if (lamp[4] == 1) { lamp_White.BackColor = Color.White; }
            //if (lamp[5] == 1) { lamp_Red.BackColor = Color.Red; }

            return Task.CompletedTask;

        }
        private Task Off_Lamp()
        {
            if (lamp[0] == 0) { lamp_Red.BackColor = Color.Silver; }
            if (lamp[1] == 0) { lamp_Blue.BackColor = Color.Silver; }
            if (lamp[2] == 0) { lamp_Green.BackColor = Color.Silver; }
            if (lamp[3] == 0) { lamp_Orange.BackColor = Color.Silver; }
            if (lamp[4] == 0) { lamp_White.BackColor = Color.Silver; }

            return Task.CompletedTask;
        }
        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void btnSelectPath_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() != DialogResult.OK)
                return;

            string folder_dis = folderBrowserDialog1.SelectedPath;
            ///
            string[] dirs = Directory.GetFiles(folder_dis, "*.csv");
            ///
            if (dirs.Length == 0) { MessageBox.Show("Can't find the file, please select the folder again.", "Can't find the file,", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
            ///
            if (dirs.Length == 0) { MessageBox.Show("CSV File Not Found, please select the folder again.", "CSV File Not Found,", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
            ///
            pathfileSignal = dirs[dirs.Length - 1];
            ///
            txtNameCSV.Text = pathfileSignal;
            ///
            _config.IniWriteValue("LogReader", "pathCSVfile", pathfileSignal);
            //string _path = SelectFile();
            /////
            //string fileExtension = GetFileExtension(_path);
            /////
            //if(fileExtension != "csv") { MessageBox.Show("Please Select path file signal again", "Select File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); txtPathFile.Text = ""; } else txtPathFile.Text = _path; 

        }
        private string SelectFile()
        {
            var dlg = new OpenFileDialog()
            {
                InitialDirectory = @"d:\",
                Filter = "Signal Files (*.csv) | *.csv | All Files (*.*) | *.*",
                RestoreDirectory = true
            };

            if (dlg.ShowDialog() != DialogResult.OK)
                return "";

            return dlg.FileName;
        }
        private string GetPathFile()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string exeName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            int firstStringPosition = exePath.IndexOf(exeName + ".exe");
            string p = exePath.Remove(firstStringPosition, System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.Length + 4);
            string _path = p + "Config.ini";

            return _path;
        }
        private string GetPath_Logfile()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string exeName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            int firstStringPosition = exePath.IndexOf(exeName + ".exe");
            string p = exePath.Remove(firstStringPosition, System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.Length + 4);
            string _path = p + "log.txt";

            return _path;
        }
        private string GetPath_Icon()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string exeName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            int firstStringPosition = exePath.IndexOf(exeName + ".exe");
            string p = exePath.Remove(firstStringPosition, System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.Length + 4);
            string _path = p + "icon.ico";

            return _path;
        }
        private string GetFileExtension(string fileName)
        {
            int dotIndex = fileName.LastIndexOf('.');
            if (dotIndex >= 0 && dotIndex < fileName.Length - 1)
            {
                return fileName.Substring(dotIndex + 1);
            }
            else
            {
                return null;
            }
        }

        private void btnTaskStart_Click(object sender, EventArgs e)
        {
            if (initailCompelte && btnEditSave.Text == "Edit")
            {
                if (!backgroundWorker1.IsBusy)
                {
                    backgroundWorker1.RunWorkerAsync();
                    ///
                    TaskRunning = true;
                    ///
                    time_Main.Enabled = true;
                    ///
                    tss_statusTask.Text = "Running...";
                }
            }
            else
            {
                MessageBox.Show("Please save and initail Config file", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void btnTask_Stop_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
                ///
                TaskRunning = false;
                ///
                tss_statusTask.Text = "Stop...";
                ///
                _fristInitail = true;
            }
        }
        private bool checkPosttime(string ieeee, string time_stamp)
        {
            bool checktime = false;
            try
            {
                string _timeCaght = _config.IniReadValue("cache", ieeee);
                ///
                if (_timeCaght == "") { return true; }
                ///
                DateTime _datetimeNow = DateTime.Parse(time_stamp.Replace("\"",""));
                ///
                DateTime _timeStampCaght = DateTime.Parse(_config.IniReadValue("cache", ieeee));
                ///
                int result = DateTime.Compare(_datetimeNow, _timeStampCaght);

                checktime = (result > 0) ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
            return checktime;
        }
        private string ieeeProductionline_Use { get; set; }
        private async void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
        {
            //var iStream = new FileStream(pathfileSignal, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            ///
            //var sr = new StreamReader(iStream);
            ///
            int loopNew = 0;
            ///
            int loopHistory = 0;
            ///
            while (TaskRunning)
            {
                try
                {
                    Application.DoEvents();
                    ///

                    if (!File.Exists(pathfileSignal))
                    {
                        continue;
                    }

                    pathfileSignalCopy = pathfileSignal.Substring(0, pathfileSignal.Length - 4) + "_1.csv";

                    if (File.Exists(pathfileSignalCopy))
                    {
                        File.Delete(pathfileSignalCopy);
                    }

                    Thread.Sleep(250);

                    File.Copy(pathfileSignal, pathfileSignalCopy);

                    //var iStream = new FileStream(pathfileSignal, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    var iStream = new FileStream(pathfileSignalCopy, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    ///
                    var sr = new StreamReader(iStream);
                    ///
                    var res = sr.ReadLine();
                    ///   
                    //if (res != null)
                    while (res != null)
                    {
                        res = sr.ReadLine();

                        if (res == null)
                        {
                            break;
                        }
                                             
                        state_PatileActive("Active!!! =>");
                        ///
                        strlistData = res.Split(new char[] { ',' });
                        ///
                        string IeeeTrue = strlistData[1];
                        ///
                        if (strlistData[0].Replace("\"", "") != "Date/Time")
                        {
                            //strlistData[1] = convertHextoBigint(strlistData[1]);
                            if (ieeeProductionline_Use == "")
                                strlistData[1] = "8375118607206191459";
                            ///
                            strlistData[1] = ieeeProductionline_Use;
                            ///

                            strlistData[1] = "8375118607206191459"; ///Test

                            if (_fristInitail)
                            {
                                if (checkPosttime(strlistData[1].Replace("\"", ""), strlistData[0].Replace("\"", "")))
                                {
                                    await Signal_toLamp(strlistData[2].Replace("\"", ""), strlistData[5].Replace("\"", ""), strlistData[4].Replace("\"", ""), strlistData[3].Replace("\"", ""), strlistData[6].Replace("\"", ""), strlistData[7].Replace("\"", ""));
                                    ///
                                    send_state(res);
                                    ///

                                    ///
                                    if (LineAlart)
                                    {
                                        //if (strlistData[2] == "1" && statusGropA == false) { line_Notify.LineNotify("A", "Machine_002: Alarm Emergency_Stop" + " " + DateTime.Now.ToString()); /*line_Notify.SendImageToGroup("A", "PIC");*/ statusGropA = true; }
                                        //if (strlistData[2] == "0" && statusGropA == true)  { line_Notify.LineNotify("A", "Machine_002: in normal" + " " + DateTime.Now.ToString()); statusGropA = false; }
                                        /////
                                        //if (strlistData[5] == "1" && statusGropB == false) { line_Notify.LineNotify("B", "Machine_001: Alarm Emergency_Stop" + " " + DateTime.Now.ToString()); /*line_Notify.SendImageToGroup("B", "PIC");*/ statusGropB = true; }
                                        //if (strlistData[5] == "0" && statusGropB == true)  { line_Notify.LineNotify("B", "Machine_001: in normal" + " " + DateTime.Now.ToString()); statusGropB = false; }

                                        string pictureName = string.Empty;

                                        if (strlistData.Length >= 15)
                                        {
                                            pictureName = strlistData[14].Replace("\"", "");
                                        }

                                        string imagePath = "";
                                        //imagePath = @"C:\TOMAS TECH\Camera Data PLC LINE NOTIFY\Master_Log\" + pictureName;
                                        imagePath = Line_Notify.pathPicture + pictureName;

                                        if (!File.Exists(imagePath) && ((strlistData[2].Replace("\"", "") == "1")
                                            || (strlistData[5].Replace("\"", "") == "1")) )
                                        {
                                            //Thread.Sleep(5000);                                            
                                        }

                                        if (strlistData[2].Replace("\"", "") == "1")
                                        {
                                            //line_Notify.LineNotify("A", "Machine_001: Alarm Emergency_Stop" + " " + DateTime.Now.ToString());
                                            //line_Notify.SendImageToGroup("A", "PIC", pictureName);
                                            //SendVideoToLineNotify(Line_Notify.token_GropA, imagePath);
                                            statusGropA = true;
                                        }
                                        //if (strlistData[2] == "0" && statusGropA == true) { line_Notify.LineNotify("A", "Machine_001: in normal" + " " + DateTime.Now.ToString()); statusGropA = false; }
                                        ///
                                        if (strlistData[5].Replace("\"", "") == "1")
                                        {
                                            //line_Notify.LineNotify("B", "Machine_002: Alarm Emergency_Stop" + " " + DateTime.Now.ToString());
                                            //line_Notify.SendImageToGroup("B", "PIC", pictureName);
                                            //SendVideoToLineNotify(Line_Notify.token_GropB, imagePath);
                                            statusGropB = true;
                                        }
                                        //if (strlistData[5] == "0" && statusGropB == true) { line_Notify.LineNotify("B", "Machine_002: in normal" + " " + DateTime.Now.ToString()); statusGropB = false; }

                                    }
                                    ///


                                    _config.IniWriteValue("cache", IeeeTrue.Replace("\"", ""), strlistData[0].Replace("\"", "")); //Record to caghe file
                                    ///
                                    PostDataAsync(strlistData);
                                    ///
                                    //PostCounterAsync(strlistData);
                                    //
                                }
                                Console.WriteLine("Line Signal history >>> " + loopHistory);
                                ///
                                loopHistory++;
                            }
                            else
                            {
                                if (checkPosttime(strlistData[1].Replace("\"", ""), strlistData[0].Replace("\"", "")))
                                {

                                    await Signal_toLamp(strlistData[2].Replace("\"", ""), strlistData[5].Replace("\"", ""), strlistData[4].Replace("\"", ""), strlistData[3].Replace("\"", ""), strlistData[6].Replace("\"", ""), strlistData[7].Replace("\"", ""));
                                    ///
                                    send_state(res);
                                    ///
                                    if (LineAlart)
                                    {
                                        //if (strlistData[2] == "1" && statusGropA == false) { line_Notify.LineNotify("A", "Machine_002: Alarm Emergency_Stop" + " " + DateTime.Now.ToString()); /*line_Notify.SendImageToGroup("A", "PIC");*/ statusGropA = true; }
                                        //if (strlistData[2] == "0" && statusGropA == true)  { line_Notify.LineNotify("A", "Machine_002: in normal" + " " + DateTime.Now.ToString()); statusGropA = false; }
                                        /////
                                        //if (strlistData[5] == "1" && statusGropB == false) { line_Notify.LineNotify("B", "Machine_001: Alarm Emergency_Stop" + " " + DateTime.Now.ToString()); /*line_Notify.SendImageToGroup("B", "PIC");*/ statusGropB = true; }
                                        //if (strlistData[5] == "0" && statusGropB == true)  { line_Notify.LineNotify("B", "Machine_001: in normal" + " " + DateTime.Now.ToString()); statusGropB = false; }

                                        string pictureName = string.Empty;

                                        if (strlistData.Length >= 15)
                                        {
                                            pictureName = strlistData[14].Replace("\"", "");
                                        }

                                        string imagePath = "";
                                        //imagePath = @"C:\TOMAS TECH\Camera Data PLC LINE NOTIFY\Master_Log\" + pictureName;
                                        imagePath = Line_Notify.pathPicture + pictureName;

                                        if (!File.Exists(imagePath) && ((strlistData[2].Replace("\"", "") == "1")
                                            || (strlistData[5].Replace("\"", "") == "1")))
                                        {
                                            //Thread.Sleep(5000);
                                        }

                                        if (strlistData[2].Replace("\"", "") == "1")
                                        {
                                            //line_Notify.LineNotify("A", "Machine_001: Alarm Emergency_Stop" + " " + DateTime.Now.ToString());
                                            //line_Notify.SendImageToGroup("A", "PIC", pictureName);
                                            //SendVideoToLineNotify(Line_Notify.token_GropA, imagePath);
                                            statusGropA = true;
                                        }
                                        //if (strlistData[2] == "0" && statusGropA == true) { line_Notify.LineNotify("A", "Machine_001: in normal" + " " + DateTime.Now.ToString()); statusGropA = false; }
                                        ///
                                        if (strlistData[5].Replace("\"", "") == "1")
                                        {
                                            //line_Notify.LineNotify("B", "Machine_002: Alarm Emergency_Stop" + " " + DateTime.Now.ToString());
                                            //line_Notify.SendImageToGroup("B", "PIC", pictureName);
                                            //SendVideoToLineNotify(Line_Notify.token_GropB, imagePath);
                                            statusGropB = true;
                                        }
                                        //if (strlistData[5] == "0" && statusGropB == true) { line_Notify.LineNotify("B", "Machine_002: in normal" + " " + DateTime.Now.ToString()); statusGropB = false; }

                                    }
                                    ///
                                    _config.IniWriteValue("cache", IeeeTrue.Replace("\"", ""), strlistData[0].Replace("\"", "")); //Record to caghe file
                                    ///
                                    PostDataAsync(strlistData);
                                    ///
                                    //PostCounterAsync(strlistData);
                                    ///
                                }
                                Console.WriteLine("Line Signal >>> " + loopNew);
                                    ///
                                    loopNew++;

                            }
                        }
                    }
                    sr.Close();
                    //else
                    //{
                        _fristInitail = false;
                        loopHistory = 0;
                        loopNew = 0;
                    //}
                }
                catch (Exception ex)
                {
                    exception_Log(ex.Message);
                }
                finally
                {
                    Task.Delay(50);
                }
            }
        }
        private string convertHextoBigint(string serialHex)
        {
            BigInteger b1 = BigInteger.Parse(serialHex, NumberStyles.AllowHexSpecifier);
            return b1.ToString();
        }
        private void disable_textbox()
        {
            txtPathParameter.Enabled = false;
            txtPathFile.Enabled = false;
            txtUrl.Enabled = false;
            txtConcurrent.Enabled = false;
            txtNameCSV.Enabled = false;
        }
        private void Enable_textbox()
        {
            txtPathParameter.Enabled = false;
            txtPathFile.Enabled = true;
            txtUrl.Enabled = true;
            txtConcurrent.Enabled = true;
            txtNameCSV.Enabled = true;
        }
        private void Write_Configfile()
        {
            try
            {
                _config.IniWriteValue("LogReader", "pathfileSignal", txtPathFile.Text);//Write Path file
                _config.IniWriteValue("LogReader", "url", txtUrl.Text);//Write Url
                _config.IniWriteValue("LogReader", "concurrent", txtConcurrent.Text);//Write Concurrent    
                _config.IniWriteValue("LogReader", "pathCSVfile", txtNameCSV.Text);//Write Concurrent              
            }
            catch
            {

            }
        }
        private void Read_Configfile()
        {
            try
            {
                folderDistination = _config.IniReadValue("LogReader", "pathfileSignal");
                url = _config.IniReadValue("LogReader", "url");
                concurrent = int.Parse(_config.IniReadValue("LogReader", "concurrent"));
                pathfileSignal = _config.IniReadValue("LogReader", "pathCSVfile");
            }
            catch
            {

            }
        }
        private void textbox_toValue()
        {
            //string fileExtension = GetFileExtension(txtPathFile.Text);
            ///
            //if (fileExtension != "csv") { MessageBox.Show("Please Select path file signal again", "Select File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
            ///
            //pathfileSignal = fileExtension;
            ///
            url = txtUrl.Text;
            ///
            try
            {
                concurrent = int.Parse(txtConcurrent.Text);
                ///
                if (concurrent == 0) { MessageBox.Show("Please input Concurrent over 0", "Input Concurrent Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
            }
            catch
            {
                return;
            }
            ValueConfrim = true;
        }
        private void Valueto_Textbox()
        {
            try
            {
                txtPathFile.Text = folderDistination;
                txtUrl.Text = url;
                txtConcurrent.Text = concurrent.ToString();
                txtNameCSV.Text = pathfileSignal;
                txtPathParameter.Text = GetPathFile();
            }
            catch
            {

            }
        }
        private void btnEditSave_Click(object sender, EventArgs e)
        {
            if (btnEditSave.Text == "Edit")
            {
                btnTask_Stop_Click(sender, e);
                ///
                Enable_textbox();
                ///
                btnSelectPath.Enabled = true;
                ///
                btnEditSave.Text = "Save";
                ///
                ValueConfrim = false;
            }
            else
            {
                textbox_toValue();
                ///
                if (ValueConfrim)
                {
                    Write_Configfile();
                    ///
                    Read_Configfile();
                    ///
                    disable_textbox();
                    ///
                    btnEditSave.Text = "Edit";
                    ///
                    initailCompelte = true;
                }
            }
        }

        private void btnSelectPathParameter_Click(object sender, EventArgs e)
        {
            string _path = SelectFile();
            string fileExtension = GetFileExtension(_path);
            ///
            try
            {
                if (fileExtension != "ini")
                {
                    MessageBox.Show("Please Select file Config again", "Select File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPathParameter.Text = "";
                    txtPathParameter.Enabled = true;
                    initailCompelte = false;
                }
                else
                {
                    txtPathParameter.Text = _path;
                    ///
                    Read_Configfile();
                    ///
                    disable_textbox();
                    ///
                    btnEditSave.Text = "Edit";
                    ///
                    initailCompelte = true;
                    ///
                    txtPathParameter.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please Select file Config again", "Select File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ///
                exception_Log(ex.Message);
                ///
                initailCompelte = false;
                ///
                txtPathParameter.Enabled = true;
            }
        }
        private void exception_Log(string mes_exception)
        {
            new Thread(() =>
            {
                txtLog_Exception.BeginInvoke(new Action(() => txtLog_Exception.Text = ""));
                ///
                txtLog_Exception.BeginInvoke(new Action(() => txtLog_Exception.Text += mes_exception + " Date Time => " + DateTime.Now.ToString() + Environment.NewLine));
                ///
                _log.LogData(mes_exception);
                ///
            }).Start();
        }
        private void reponse_state(string reponse)
        {
            new Thread(() =>
            {
                txtResponse.BeginInvoke(new Action(() => txtResponse.Text = ""));
                ///
                Task.Delay(10);
                ///
                txtResponse.BeginInvoke(new Action(() => txtResponse.Text += reponse + " Date Time => " + DateTime.Now.ToString() + Environment.NewLine));
                ///
            }).Start();
        }
        private void send_state(string state)
        {
            new Thread(() =>
            {
                txtState_toPHP.BeginInvoke(new Action(() => txtState_toPHP.Text = ""));
                ///
                Task.Delay(10);
                ///
                txtState_toPHP.BeginInvoke(new Action(() => txtState_toPHP.Text += state + " Date Time => " + DateTime.Now.ToString() + Environment.NewLine));
                ///
            }).Start();
        }
        private void state_PatileActive(string state)
        {
            new Thread(() =>
            {
                statusStrip1.BeginInvoke(new Action(() => stt_PatlieActive.Text = ""));
                ///
                Task.Delay(10);
                ///
                statusStrip1.BeginInvoke(new Action(() => stt_PatlieActive.Text += state + " Date Time => " + DateTime.Now.ToString()));
                ///
            }).Start();
        }
        private async void time_Main_Tick(object sender, EventArgs e)
        {
            await UpdateLamp();
            ///
            //string[] dirs = Directory.GetFiles(folderDistination, "*.csv");
            ///
            try
            {
                //if (dirs[dirs.Length - 1] != pathfileSignal)
                //{
                //    pathfileSignal = dirs[dirs.Length - 1];
                //    ///
                //    Valueto_Textbox();
                //    ///
                //    Write_Configfile();
                //    ///
                //    Read_Configfile();
                //    ///
                //    disable_textbox();
                //    ///
                //    initailCompelte = true;
                //}

                
                    pathfileSignal = folderDistination + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
                    ///
                    Valueto_Textbox();
                    ///
                    Write_Configfile();
                    ///
                    Read_Configfile();
                    ///
                    disable_textbox();
                    ///
                    initailCompelte = true;
                


            }
            catch
            {

            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            //exception_Log("Error");
        }
        private Task Gendata()
        {
            for (int i = 0; i < 20000; i++)
            {
                string datetime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
                ///
                DumpToCsvFile(datetime + ",743A65FFFE4A1688,0,0,0,0,0,0,9,0,,,0,0");
                ///

            }
            return Task.CompletedTask;
        }
        public void DumpToCsvFile(string Dataresult)
        {
            var csv = new StringBuilder();
            var Newline = string.Format("{0}", Dataresult);
            csv.AppendLine(Newline);
            ///
            File.AppendAllText(pathfileSignal, csv.ToString());
        }
        private void AssignID_Machine()
        {
            ieeeProductionline[0] = "8375118607206191459";
            //ieeeProductionline[0] = "743A65FFFE4A1688";
            ieeeProductionline[1] = "8375118607206215079";
            ieeeProductionline[2] = "8375118607206191460";
            ieeeProductionline[3] = "8375118607206215080";
            ieeeProductionline[4] = "8375118607206191461";
            ieeeProductionline[5] = "8375118607206215081";
            ieeeProductionline[6] = "8375118607206191462";
            ieeeProductionline[7] = "8375118607206215082";
            ieeeProductionline[8] = "8375118607206191463";
            ieeeProductionline[9] = "8375118607206215083";
            ieeeProductionline[10] = "8375118607206191464";
            ieeeProductionline[11] = "8375118607206215084";
        }
        string[] ieeeProductionline = new string[13];
        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int x = checkedListBox1.SelectedIndex;
            ///
            checkedListBox1.SetItemChecked(x, true);
            ///
            ieeeProductionline_Use = ieeeProductionline[x];
            ///
            lblProductionID.Text = ieeeProductionline_Use;
            ///
            for (int i = 0; i <= 12; i++)
            {
                if (i != x)
                {
                    checkedListBox1.SetItemChecked(i, false);
                }
            }
        }
        public string token_GropA = "biVeLL1cyabxhMslTq9UFz2cpEDQwC2YDGXXSKZmoRF";
        public string VideoPath = @"D:\MACHINE_IMAGE\MC001\BUSHING_ER001.mp4";
        public string Folder = @"D:\MACHINE_IMAGE\MC001";
        private void button2_Click(object sender, EventArgs e)
        {
            //line_Notify.LineNotify("A", "AUTO STOP: Bushing error" + " " + DateTime.Now.ToString()); //line_Notify.SendImageToGroup("A","V"); statusGropA = true;
            ///
            //string[] filename = File.ReadAllLines(Folder);
            ///
            //string[] dirs = Directory.GetFiles(Folder);
            string[] dirs = Directory.GetFiles(Folder, "*.mp4");
            ///
            SendVideoToLineNotify(token_GropA, dirs[dirs.Length - 1]);
        }
        public async void SendVideoToLineNotify(string token, string filePath)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                using (var form = new MultipartFormDataContent())
                {
                    // อ่านข้อมูลวีดีโอจากไฟล์

                    byte[] videoBytes = File.ReadAllBytes(filePath);

                    using (var videoContent = new ByteArrayContent(videoBytes))
                    {
                        videoContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application /octet-stream");

                        // เพิ่มไฟล์วีดีโอในเนื้อหาแบบ MultipartFormData

                        form.Add(videoContent, "video", Path.GetFileName(filePath));

                        // ส่งข้อมูลไปยัง LINE Notify API
                        string apiUrl = "https://notify-api.line.me/api/notify";
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                        HttpResponseMessage response = await httpClient.PostAsync(apiUrl, form);

                        // ตรวจสอบการตอบกลับจากเซิร์ฟเวอร์
                        if (response.IsSuccessStatusCode)
                        {
                            Console.WriteLine("Video sent successfully.");
                        }
                        else
                        {
                            Console.WriteLine("Failed to send video. Error: " + response.ReasonPhrase);
                        }
                    }
                }
            }
        }

        private void chk_linenotify_CheckedChanged(object sender, EventArgs e)
        {
            LineAlart = chk_linenotify.Checked;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (File.Exists(pathfileSignalCopy))
                {
                    File.Delete(pathfileSignalCopy);
                }
            }
            catch (Exception)
            {
               
            }
           
            btnTask_Stop_Click(sender, e);
            Thread.Sleep(50);
        }
    }
}
