using AR;
using Project.Dialog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Windows.Forms;
using UIControl;
using static Project.Dialog.Debug.fSendInboutData;

namespace Project
{
    public partial class FMain : Form
    {
        Boolean camliveBusy = false;
        bool liveviewprocesson = false;
        Stopwatch watFps = new Stopwatch();
        Stopwatch watFps0 = new Stopwatch();
        Stopwatch watFps1 = new Stopwatch();
        Stopwatch watFps2 = new Stopwatch();

        System.Threading.Thread thConnection;   //Connection check
        byte ConnectSeq = 0;
        DateTime AirOffStart = DateTime.Parse("1982-11-23");
        DateTime EmergencyTime = DateTime.Now;
        Dialog.fLog logForm = null;

        Dialog.fSystem_Setting frmSysParam = null;
        Dialog.fSystem_MotParameter frmSysMotParam = null;
        delegate void SelectModelHandler(string modelName, bool bUploadConfig);


        public FMain()
        {
            InitializeComponent();
            PUB.initCore();



            //AddLiveviewControl();

            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
                else if (e1.KeyCode == Keys.F1 && e1.Control && e1.Shift)
                {
                    Boolean debug = PUB.flag.get(eVarBool.FG_DEBUG);
                    PUB.flag.set(eVarBool.FG_DEBUG, !debug, "FMAIN_SECRETKEY");
                    ShowDebugMenu();
                }
                else if (e1.KeyCode == Keys.F2 && e1.Control && e1.Shift) menu_logform();
                else if (e1.KeyCode == Keys.F5) btStart.PerformClick();
                else if (e1.KeyCode == Keys.F8) btJobCancle.PerformClick();
                else if (e1.KeyCode == Keys.F9) btStart.PerformClick();

                if (DateTime.Now > PUB.LastInputTime) PUB.LastInputTime = DateTime.Now;
            };

            //dotList = new List<arCtl.arLabel>();
            //dotList.AddRange(new arCtl.arLabel[] { lbDot1, lbDot2, lbDot3, lbDot4, lbDot5, lbDot6, lbDot7, lbDot8, lbDot9, lbDot10 });

            this.MouseMove += (s1, e1) => { if (DateTime.Now > PUB.LastInputTime) PUB.LastInputTime = DateTime.Now; };
            this.FormClosing += __Closing;

            if (AR.SETTING.Data.FullScreen) this.WindowState = FormWindowState.Maximized;
            else this.Size = new Size(1280, 1024);

            //this.lbTitle.MouseMove += LbTitle_MouseMove;
            //this.lbTitle.MouseUp += LbTitle_MouseUp;
            //this.lbTitle.MouseDown += LbTitle_MouseDown;
            //this.lbTitle.DoubleClick += LbTitle_DoubleClick;
        }

        void ShowDebugMenu()
        {
            Boolean debug = PUB.flag.get(eVarBool.FG_DEBUG);
            this.btDebug.Visible = debug;
            this.hmi1.arDebugMode = debug;
            //this.rtStatusMessage.Visible = debug;
            //this.panel1.Visible = debug;
        }

        private void __Closing(object sender, FormClosingEventArgs e)
        {
            PUB.popup.needClose = true;
            if (PUB.sm.Step == eSMStep.RUN)
            {
                UTIL.MsgE("Cannot exit while system is running.");
                e.Cancel = true;
                return;
            }
            if (PUB.sm.Step < eSMStep.CLOSING)
            {
                var rlt = UTIL.MsgQ("Do you want to exit?");
                if (rlt != System.Windows.Forms.DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
                _Close_Start();
            }
        }

        void UpdateControl()
        {
            this.RtLog.DateFormat = "HH:mm:ss";
            this.RtLog.BackColor = SystemColors.Window;
            this.RtLog.ColorList = new arCtl.sLogMessageColor[] {
                new arCtl.sLogMessageColor("BARCODE",Color.DarkMagenta),
                new arCtl.sLogMessageColor("ERR",Color.Red),
                new arCtl.sLogMessageColor("NORMAL", Color.Black),
                new arCtl.sLogMessageColor("WARN", Color.DarkMagenta),
                new arCtl.sLogMessageColor("ATT", Color.Tomato),
                new arCtl.sLogMessageColor("INFO", Color.MidnightBlue),
                new arCtl.sLogMessageColor("VIS", Color.Blue),
                new arCtl.sLogMessageColor("SM", Color.Indigo),
                new arCtl.sLogMessageColor("WATCH", Color.Indigo),
            };

            var colname = new string[] { "RID", "SID", "QTY", "VNAME", "VLOT", "MFG", "PART" };
            var row = 1;
            foreach (var col in colname)
            {
                listView21.SetText(row, 0, col);
                listView21.SetText(row, 2, col);
                listView21.SetText(row, 4, col);

                listView21.SetText(row, 1, string.Empty);
                listView21.SetText(row, 3, string.Empty);
                listView21.SetText(row, 5, string.Empty);

                row += 1;
            }
            listView21.SetText(row, 0, "SIZE");
            listView21.SetText(row, 2, "SIZE");
            row += 1;

            var row2 = row;
            foreach (var col in colname)
            {
                listView21.SetText(row2, 0, col);
                //listView21.SetText(row, 2, col);
                listView21.SetText(row2, 4, col);

                listView21.SetText(row2, 1, string.Empty);
                listView21.SetText(row2, 3, string.Empty);
                listView21.SetText(row2, 5, string.Empty);

                row2 += 1;
            }

            colname = new string[] { "DEG", "QR", "BCD", "REGEX", "", "", "" };
            foreach (var col in colname)
            {
                listView21.SetText(row, 2, col);
                listView21.SetText(row, 3, string.Empty);
                row += 1;
            }

            TowerLamp.Enable = !AR.SETTING.Data.Disable_TowerLamp;

            if (VAR.BOOL[eVarBool.Use_Conveyor])
            {
                hmi1.arVar_Port[0].MotorDir = true;
                hmi1.arVar_Port[2].MotorDir = true;
            }

            //UI changes based on whether 2 Keyence units are used
            if (SETTING.Data.Keyence_IPR.isEmpty())
            {
                keyenceviewR.Visible = false;
                keyenceviewF.Dock = DockStyle.Fill;
            }
            else
            {
                keyenceviewR.Visible = true;
                keyenceviewF.Dock = DockStyle.Right;
            }
            if (VAR.BOOL[eVarBool.Use_Conveyor])
            {
                lbLock0.Visible = false;
                lbLock2.Visible = false;
                arLabel6.Text = "▲";
                arLabel11.Text = "■";
                arLabel74.Text = "▲";
                arLabel76.Text = "■";
                SETTING.Data.Disable_PortL = true;
                SETTING.Data.Disable_PortR = true;
            }
            else
            {
                lbLock0.Visible = true;
                lbLock2.Visible = true;
                arLabel6.Text = "▼";
                arLabel11.Text = "▲";
                arLabel74.Text = "▼";
                arLabel76.Text = "▲";
                SETTING.Data.Disable_PortL = false;
                SETTING.Data.Disable_PortR = false;

            }
        }


        //void RefreshList()
        //{
        //    // 비동기로 실행
        //    Task.Run(async () => await RefreshListAsync());
        //}

        async Task RefreshList()
        {
            //if (COMM.SETTING.Data.OnlineMode == false) return;

            // ProgressBar 표시
            this.BeginInvoke(new Action(() =>
            {
                if (progressBarRefresh != null)
                {
                    progressBarRefresh.Visible = true;
                    progressBarRefresh.Style = ProgressBarStyle.Marquee;
                    progressBarRefresh.MarqueeAnimationSpeed = 30;
                }
            }));

            VAR.TIME[eVarTime.REFRESHLIST] = DateTime.Now;

            try
            {
                var dtstr = DateTime.Now.ToShortDateString();

                if (AR.SETTING.Data.OnlineMode)
                {
                    try
                    {
                        await Task.Run(() =>
                        {
                            var ta = new DataSet1TableAdapters.K4EE_Component_Reel_ResultTableAdapter();
                            ta.FillByLen7(this.dataSet1.K4EE_Component_Reel_Result, dtstr, dtstr, AR.SETTING.Data.McName);
                        });
                    }
                    catch (Exception ex)
                    {
                        PUB.log.AddE($"DB History Request Error" + ex.Message);
                    }
                }

                // UI 업데이트는 UI 스레드에서
                this.BeginInvoke(new Action(() => ListFormmatData()));

                var TS1 = VAR.TIME.RUN(eVarTime.REFRESHLIST);
                PUB.log.AddI(string.Format($"List refresh({0} items) {TS1.TotalSeconds:N1}s", dataSet1.K4EE_Component_Reel_Result.Count));
            }
            catch (Exception ex)
            {
                PUB.log.AddE("List refresh failed:" + ex.Message);
            }
            finally
            {
                // ProgressBar 숨기기
                this.BeginInvoke(new Action(() =>
                {
                    if (progressBarRefresh != null)
                    {
                        progressBarRefresh.Visible = false;
                    }
                }));
            }
        }

        void ListFormmatData()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(ListFormmatData));
                return;
            }

            PUB.log.Add($"ListFormmatData");

            arDatagridView1.SuspendLayout();

            try
            {
                foreach (DataGridViewRow item in this.arDatagridView1.Rows)
                {
                    var drv = item.DataBoundItem as System.Data.DataRowView;
                    var dr = drv.Row as DataSet1.K4EE_Component_Reel_ResultRow;

                    if (dr.REMARK.StartsWith("(BYPASS"))
                    {
                        item.DefaultCellStyle.BackColor = Color.LightSkyBlue;
                    }
                    else
                    {
                        if (dr.LOC == "L")
                            item.DefaultCellStyle.BackColor = Color.FromArgb(220, 220, 220);
                        else
                            item.DefaultCellStyle.BackColor = Color.FromArgb(250, 250, 250);
                    }

                    if (dr.REMARK.StartsWith("(BYPASS"))
                        item.DefaultCellStyle.ForeColor = Color.Black;
                    else if (dr.PRNATTACH == false)
                        item.DefaultCellStyle.ForeColor = Color.FromArgb(0xfe, 0x2a, 0x00);
                    else if (dr.PRNVALID == false)
                        item.DefaultCellStyle.ForeColor = Color.FromArgb(0x1f, 0x3b, 0x34);
                    else
                        item.DefaultCellStyle.ForeColor = Color.Black;
                }
            }
            catch (Exception ex)
            {

            }

            arDatagridView1.ResumeLayout();
        }
        async private void __Load(object sender, EventArgs e)
        {


            this.Text = Application.ProductName + " ver " + Application.ProductVersion + " " + Application.CompanyName;
            PUB.init(); //public initialize

            VAR.BOOL[eVarBool.Use_Conveyor] = SETTING.User.useConv;
            groupBox3.Text = $"Model Info({AR.SETTING.Data.McName})";

            UpdateControl();
            PUB.log.RaiseMsg += Log_RaiseMsg;
            PUB.logKeyence.RaiseMsg += Log_RaiseMsg;
            PUB.logWS.RaiseMsg += LogWS_RaiseMsg;


            this.Show();
            Application.DoEvents();
            //  sbDevice.Text = "";
            SetStatusMessage("Program initialization", Color.White, Color.White, Color.Tomato, Color.Black);



            //Initialize picker status
            foreach (var item in this.hmi1.arVar_Picker)
                item.Clear();

            //Initialize port status
            foreach (var item in this.hmi1.arVar_Port)
                item.Clear();


            PUB.flag.set(eVarBool.FG_DEBUG, true, "Under development");
            ShowDebugMenu();

            ////'Application.DoEvents();

            //setting dio events
            PUB.dio.IOValueChanged += Dio_IOValueChanged;
            PUB.dio.Message += _DIO_IOMessage;

            //setting mot events
            PUB.mot.Message += mot_Message;
            PUB.mot.HomeStatusChanged += mot_HomeStatusChanged;
            PUB.mot.AxisMoveValidateCheck += mot_AxisMoveValidateCheck;
            PUB.mot.PositionChanged += Mot_PositionChanged;
            PUB.mot.StatusChanged += mot_StatusChanged;
            PUB.mot.EndStatusChanged += Mot_EndStatusChanged;

            //remote control
            PUB.remocon = new arDev.RS232("R");
            PUB.remocon.Terminal = arDev.RS232.eTerminal.LF;
            //Pub.remocon.ReceiveData += remocon_ReceiveData;

            PUB.BarcodeFix = new arDev.RS232("B");
            PUB.BarcodeFix.Terminal = arDev.RS232.eTerminal.LF;
            PUB.BarcodeFix.ReceiveData += BarcodeFix_ReceiveData;

            var portinfo = AR.SETTING.Data.Serial_Remocon.Split(':');
            PUB.remocon.PortName = portinfo[0];
            if (portinfo.Length > 1) PUB.remocon.BaudRate = int.Parse(portinfo[1]);
            else PUB.remocon.BaudRate = 9600;
            if (PUB.remocon.Open() == false) PUB.log.AddAT("Debug port open failed(" + AR.SETTING.Data.Serial_Remocon + ")");
            else PUB.log.Add("Debug port open successful(" + AR.SETTING.Data.Serial_Remocon + ")");


            PUB.log.Add("State machine started");
            PUB.sm.SetMsgOptOff(); //Disable all message output. (Events still function)
            PUB.sm.Running += SM_Loop;
            PUB.sm.SPS += SM_SPS;

            //######################################################
            //########## The following events are defined in _11_SM_Events.cs file
            //######################################################
            PUB.sm.StepChanged += SM_StepChanged;
            PUB.sm.Message += SM_Message;
            PUB.sm.InitControl += SM_InitControl;
            PUB.sm.StepStarted += SM_StepStarted;
            PUB.sm.StepCompleted += SM_StepCompleted;
            PUB.sm.StateProgress += SM_StateProgress;
            PUB.sm.Start();

            //Flag value changes
            //PUB.flag.ValueChanged += Flag_ValueChanged;
            VAR.BOOL.ValueChanged += Flag_ValueChanged;

            //ILock value changes
            for (int i = 0; i < PUB.iLock.Length; i++)
                PUB.iLock[i].ValueChanged += Lock_ValueChanged;

            //ILock value changes
            PUB.iLockPRL.ValueChanged += Lock_ValueChanged;
            PUB.iLockPRR.ValueChanged += Lock_ValueChanged;
            PUB.iLockVS0.ValueChanged += Lock_ValueChanged;
            PUB.iLockVS1.ValueChanged += Lock_ValueChanged;
            PUB.iLockVS2.ValueChanged += Lock_ValueChanged;

            PUB.iLockCVL.ValueChanged += Lock_ValueChanged;
            PUB.iLockCVR.ValueChanged += Lock_ValueChanged;

            hmi1.ClearMenu();
            hmi1.Message += loader1_Message;
            hmi1.IConClick += loader1_IConClick;
            hmi1.ButtonClick += Loader1_ButtonClick;

            PUB.plc = new AR.MemoryMap.Client(SETTING.Data.swplc_name, SETTING.Data.swplc_size);
            PUB.plc.ValueChanged += Plc_ValueChanged;
            PUB.plc.Start();

            VAR.I32[eVarInt32.Front_Laser_Cleaning] += 1;

            //Keyence connection
            if (SETTING.Data.Keyence_IPF.isEmpty() == false)
            {
                PUB.keyenceF = new Device.KeyenceBarcode(AR.SETTING.Data.Keyence_IPF);
                PUB.keyenceF.Tag = "F";
                PUB.keyenceF.Connect();
                PUB.keyenceF.BarcodeRecv += Keyence_BarcodeRecv;
                PUB.keyenceF.ImageRecv += Keyence_ImageRecv;
            }

            if (SETTING.Data.Keyence_IPR.isEmpty() == false)
            {
                PUB.keyenceR = new Device.KeyenceBarcode(AR.SETTING.Data.Keyence_IPR);
                PUB.keyenceR.Tag = "R";
                PUB.keyenceR.Connect();
                PUB.keyenceR.BarcodeRecv += Keyence_BarcodeRecv;
                PUB.keyenceR.ImageRecv += Keyence_ImageRecv;
            }

            tmDisplay.Start(); //start Display

            PUB.AddSystemLog(Application.ProductVersion, "SCREEN", "Message");

            PUB.log.Add("Program Start");
            if (SETTING.Data.OnlineMode)
                PUB.CheckNRegister3(Application.ProductName, "chi", Application.ProductVersion);
            else PUB.GetIPMac();

            if (SETTING.Data.EnableDebugMode)
            {
                btDebug.Visible = true;
                PUB.flag.set(eVarBool.FG_DEBUG, true, "FMAIN_STARTUP");
                // menu_logform();
            }

            //swPLC program execution
            var swplcfile = UTIL.MakePath("swplc", "SoftwarePLC.exe");
            if (System.IO.File.Exists(swplcfile))
            {
                UTIL.RunProcess(swplcfile);
            }
            else PUB.log.AddE($"No SoftwarePLC Execute File({swplcfile})");

            await RefreshList();
            UpdateControl();
            PUB.flag.set(eVarBool.FG_ENABLE_LEFT, !AR.SETTING.Data.Disable_Left, "LOAD");
            PUB.flag.set(eVarBool.FG_ENABLE_RIGHT, !AR.SETTING.Data.Disable_Right, "LOAD");

            //Connection check thread
            var thStart = new System.Threading.ThreadStart(bwDeviceConnection);
            thConnection = new System.Threading.Thread(thStart);
            thConnection.IsBackground = true;
            thConnection.Start();


            fwebview = new fWebView();
            fwebview.Show();
        }

        Dialog.fWebView fwebview = null;

        // 웹 UI에 이벤트 전송
        public void SendWebEvent(string eventType, object data = null)
        {
            if (fwebview != null)
            {
                this.BeginInvoke(new Action(() =>
                {
                    fwebview.BroadcastEvent(eventType, data);
                }));
            }
        }

        private void Plc_ValueChanged(object sender, AR.MemoryMap.Core.monitorvalueargs e)
        {
            //
        }

        private void BarcodeFix_ReceiveData(object sender, arDev.RS232.ReceiveDataEventArgs e)
        {
            var data = e.StrValue.Replace("\r", "").Replace("\n", "");
            bool findregex = false;
            PUB.log.Add($"Fixed barcode received\n{data}");

            Tuple<int, List<string>> cnt = null;
            bool IgnoreBarcode = false;
            lock (PUB.Result.BCDPatternLock)
            {
                cnt = BarcodeRegExProcess(
                            PUB.Result.BCDPattern,
                            PUB.Result.BCDIgnorePattern,
                            PUB.Result.ItemDataC.VisionData, string.Empty, data, out IgnoreBarcode, out findregex);
            }


            if (IgnoreBarcode) PUB.log.AddE("This is an ignore barcode");
            else if (cnt.Item1 == 0) PUB.log.AddAT("(Manual) No applicable barcode value");
            else PUB.log.Add($"(Manual) Barcode applied count:{cnt.Item1}");

            //Find patterns that are compatible with other models
            if ((cnt?.Item1 ?? 0) == 0)
            {
                var patterns = PUB.GetPatterns("%", false);
                PUB.log.Add("==============");
                cnt = BarcodeRegExProcess(patterns, new System.Collections.Generic.List<Class.RegexPattern>(), null, string.Empty, data, out bool igBarcode, out findregex);
                if (cnt.Item1 > 0)
                {
                    PUB.log.AddI("Compatible with the following barcode");
                    foreach (var item in cnt.Item2)
                    {
                        PUB.log.Add($"Model:{item}");
                    }

                    //If there is 1 data item and the name is different from current model, recommend it
                    if (cnt.Item2.Count == 1 && AR.SETTING.Data.Enable_AutoChangeModelbyHandBarcode)
                    {
                        var modelname = cnt.Item2[0].Split('|')[0];
                        if (PUB.Result.isSetvModel && modelname.Equals(PUB.Result.vModel.Title))
                        {
                            //Same barcode, no additional work needed
                        }
                        else
                        {
                            if (PUB.mdm.dataSet.OPModel.Where(t => t.Title.Equals(modelname)).Any())
                            {
                                PUB.log.Add($"Model auto-switch (fixed barcode)");
                                PUB.SelectModelV(modelname);
                            }
                        }
                    }

                }
            }
        }

        void loader1_Message(object sender, HMI.MessageArgs e)
        {
            //Message generated from loader
            if (e.isError) PUB.log.AddE(e.Message);
            else PUB.log.Add(e.Message);
        }

        private void Log_RaiseMsg(DateTime LogTime, string TypeStr, string Message)
        {
            if (Message.Contains("ignore")) return;
            if (Message.StartsWith("1:")) return;
            if (Message.StartsWith("11:")) return;

            this.RtLog.AddMsg(LogTime, TypeStr, Message);
        }
        private void LogWS_RaiseMsg(DateTime LogTime, string TypeStr, string Message)
        {
            this.RtLog.AddMsg(LogTime, TypeStr, Message);
        }


        /// <summary>
        /// soft reset value & use
        /// </summary>
        void UpdateSoftLimit()
        {
            PUB.log.Add("Motion SOFT-LIMIT setting");

            for (short i = 0; i < PUB.mot.DeviceCount; i++)
            {
                if (PUB.system_mot.UseAxis(i) == false)
                {
                    PUB.mot.SetUse(i, false);
                }
                else
                {
                    PUB.mot.SetUse(i, true);
                    if (PUB.system_mot.SWLimit(i) > 0)
                        PUB.mot.SetSoftLimit((short)i, true, PUB.system_mot.SWLimit(i), -9999);
                    else
                        PUB.mot.SetSoftLimit((short)i, false, 0, 0);
                }
            }

        }

        void Func_sw_initialize()
        {
            PUB.Result.ResetButtonDownTime = DateTime.Now;
            if (PUB.sm.Step == eSMStep.RUN)
            {
                PUB.popup.setMessage("SYSTEM INNITIALIZE\n" +
                    "Cannot execute [Initialize] during operation\n" +
                    "Method #1 => Use [Stop] button to stop system then retry\n" +
                    "Method #2 => Switch to [Manual Execution] mode then retry");
            }
            else if (
                PUB.sm.getNewStep != eSMStep.HOME_FULL &&
                PUB.sm.Step != eSMStep.HOME_FULL)
            {
                PUB.log.Add("Switching system status to RESET");
                PUB.AddSystemLog(Application.ProductVersion, "MAIN", "SYSTEM RESET");
                PUB.sm.SetNewStep(eSMStep.HOME_FULL);
            }
            else PUB.log.AddAT("RESET button ignored because system is already in RESET state.");
        }


        /// <summary>
        /// Task selection before starting work
        /// </summary>
        void Func_start_job_select()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(Func_start_job_select), null);
            }
            else
            {
                //Clear log window
                if (this.RtLog.InvokeRequired) RtLog.BeginInvoke(new Action(() => { RtLog.Clear(); }));
                else this.RtLog.Clear();

                //PUB.popup.needClose = true;
                //PUB.flag.set(eVarBool.RUN_INIT, false, "FN_JOBSELECT");
                //PUB.ClearRunStep(0);
                //PUB.ClearRunStep(1);

                if (DIO.GetIOInput(eDIName.PICKER_SAFE) == false)
                {
                    PUB.Result.SetResultMessage(eResult.OPERATION, eECode.NEED_JOBCANCEL, eNextStep.ERROR);
                    return;
                }


                var sb = new System.Text.StringBuilder();
                if (PUB.mot.IsInit == false) sb.AppendLine("▶ Motion board not initialized.\nPlease contact support");
                if (PUB.dio.IsInit == false) sb.AppendLine("▶ I/O board not initialized.\nPlease contact support");
                if (DIO.GetIOOutput(eDOName.SOL_AIR) == false) sb.AppendLine("▶ AIR output not active (Press the AIR button on the front panel)");
                if (DIO.GetIOInput(eDIName.AIR_DETECT) == false) sb.AppendLine("▶ AIR not detected (Check AIR input and output status)");

                if (PUB.mot.HasHomeSetOff == true) sb.AppendLine("▶ There are axes that have not completed home search (Execute device initialization first)");

                if (sb.Length > 0)
                {
                    PUB.Result.SetResultMessage(eResult.HARDWARE, eECode.MESSAGE_ERROR, eNextStep.ERROR, sb.ToString());
                    return;
                }

                //Allow user to select work type

                Form f;

                using (f = new Dialog.fSelectJob())
                    if (f.ShowDialog() == DialogResult.OK)
                    {
                        PUB.sm.SetNewStep(eSMStep.RUN);
                    }
                    else
                    {
                        PUB.log.AddAT("User cancelled at task selection screen before starting work");

                    }
            }
        }


        private void systemParameterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frmSysParam == null || frmSysParam.IsDisposed || frmSysParam.Disposing)
            {
                if (frmSysParam != null) frmSysParam.FormClosed -= frmSysParam_FormClosed;
                frmSysParam = new Dialog.fSystem_Setting();
                frmSysParam.FormClosed += frmSysParam_FormClosed;
            }
            frmSysParam.Show();
            frmSysParam.Activate();
            if (frmSysParam.WindowState == FormWindowState.Minimized)
                frmSysParam.WindowState = FormWindowState.Normal;
        }

        void frmSysParam_FormClosed(object sender, FormClosedEventArgs e)
        {
            var f = sender as Form;
            if (f.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                UpdateSoftLimit();
            }
        }

        void CheckFreeSpace()
        {
            try
            {
                double freeSpaceRate_ = 0;
                var path = PUB.getSavePath(out freeSpaceRate_);
                if (path.StartsWith("\\"))
                {
                    hmi1.arFreespace = 0.0;
                }
                else
                {
                    hmi1.arFreespace = freeSpaceRate_;//
                    if (freeSpaceRate_ < AR.SETTING.Data.AutoDeleteThreshold)
                    {
                        PUB.flag.set(eVarBool.FG_MINSPACE, true, "CheckFreeSpace");
                        hmi1.arLowDiskSpace = true;
                    }
                    else
                    {
                        PUB.flag.set(eVarBool.FG_MINSPACE, false, "CheckFreeSpace");
                        hmi1.arLowDiskSpace = false;
                    }
                }
            }
            catch (Exception ex)
            {
                hmi1.arFreespace = 0.0;
                PUB.log.AddE("check free space : " + ex.Message);
            }
        }
        private void demoRunToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var item = new Class.JobData(0) { };
            SaveData_EE(item, "L", "TEST", "debug");

        }
        private void arLabel2_Click_1(object sender, EventArgs e)
        {
            var ctl = sender as arCtl.arLabel;
            if (ctl.Enabled == false) return;
            PUB.log.Add("User Click : Start", false);
            _BUTTON_START();
        }

        private void arLabel4_Click_1(object sender, EventArgs e)
        {
            PUB.log.Add("User Click : Stop", false);
            _BUTTON_STOP();
        }

        private void btReset_Click(object sender, EventArgs e)
        {
            PUB.log.Add("User Click : Reset", false);
            _BUTTON_RESET();
        }

        void menu_logform()
        {
            if (logForm == null || logForm.IsDisposed == true || logForm.Disposing == true)
                logForm = new Dialog.fLog();
            if (logForm.WindowState == FormWindowState.Minimized) logForm.WindowState = FormWindowState.Normal;
            logForm.Show();
        }


        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            menu_logform();
        }



        private void arLabel10_Click_1(object sender, EventArgs e)
        {
            if (PUB.sm.isRunning == true)
            {
                UTIL.MsgE("AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");
                return;
            }

            this.Close();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (PUB.flag.get(eVarBool.FG_INIT_MOTIO) == false)
            {
                UTIL.MsgE("Motion not initialized\nPlease try again later");
                return;
            }
            var cur = DIO.GetIOOutput(eDOName.ROOMLIGHT);
            DIO.SetRoomLight(!cur, true);
        }

        Dialog.fHistory fhist = null;
        private void button3_Click(object sender, EventArgs e)
        {
            if (fhist == null || fhist.IsDisposed)
                fhist = new Dialog.fHistory();

            fhist.Show();
            fhist.Activate();
            if (fhist.WindowState == FormWindowState.Minimized)
                fhist.WindowState = FormWindowState.Maximized;

            //f.Show();
            //var file = System.IO.Path.Combine(UTIL.CurrentPath, "ResultView", "ResultView.exe");
            //if (System.IO.File.Exists(file) == false)
            //{

            //    PUB.popup.setMessage("Result Viewer Error\nResult viewer file does not exist\nPlease contact developer (T.8567)\nFile : " + file);
            //    return;
            //}
            //UTIL.RunProcess(file);
        }

        private void button4_Click(object sender, EventArgs e)
        {

        }


        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {

        }

        private void arLabel13_Click(object sender, EventArgs e)
        {
            UTIL.ScreenCapture(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height, new Point(0, 0));
        }

        void menu_cancel()
        {

            if (PUB.flag.get(eVarBool.FG_INIT_MOTIO) == false)
            {
                UTIL.MsgE("Motion not initialized\nPlease try again later");
                return;
            }

            var msg = new System.Text.StringBuilder();


            if (PUB.mot.HasHomeSetOff)
            {
                msg.AppendLine("! Device initialization is not complete\n! Execute device initialization");
            }

            if (PUB.sm.isRunning == true)
            {
                msg.AppendLine("! " + "AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");
            }

            ////if (PUB.sm.Step == eSMStep.PAUSE)
            ////{
            ////	msg.AppendLine("! Press RESET and try again");
            ////}

            if (DIO.IsEmergencyOn() == true)
            {
                msg.AppendLine("! Release emergency stop");
            }

            if (DIO.isSaftyDoorF() == false)
            {
                msg.AppendLine("! Front door is open");
            }

            if (DIO.isSaftyDoorR() == false)
            {
                msg.AppendLine("! Rear door is open");
            }

            if (msg.Length > 0)
            {
                UTIL.MsgE(msg.ToString());
                PUB.log.AddE(msg.ToString());
                return;
            }

            msg.Clear();
            msg.AppendLine("Q. Cancel work and execute motion position initialization?");
            var dlgresult = UTIL.MsgQ(msg.ToString());
            if (dlgresult != System.Windows.Forms.DialogResult.Yes) return;

            PUB.log.Add("User Click : tray out & clear position", false);
            Run_MotionPositionReset();
        }

        void Run_MotionPositionReset()
        {
            PUB.flag.set(eVarBool.FG_USERSTEP, false, "Run_MotionPositionReset");
            PUB.log.AddAT("Starting discharge and home movement");
            PUB.AddSystemLog(Application.ProductVersion, "MAIN", "Cancel Work");
            PUB.sm.SetNewStep(eSMStep.HOME_QUICK);//Change to execution mode
        }

        private void arLabel14_Click(object sender, EventArgs e)
        {
            if (PUB.flag.get(eVarBool.FG_INIT_MOTIO) == false)
            {
                UTIL.MsgE("Motion not initialized\nPlease try again later");
                return;
            }
            var msg = new System.Text.StringBuilder();

            if (PUB.sm.isRunning == true)
                msg.AppendLine("*" + "AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");

            if (DIO.GetIOOutput(eDOName.SOL_AIR) == false)
                msg.AppendLine("* Press the AIR button on the front to supply AIR");

            //if (DIO.GetIOOutput(eDOName.SOL_AIR) && DIO.GetIOInput(eDIName.AIR_DETECT) == false)
            //    msg.AppendLine("* AIR not detected, please check AIR supply status");
            if (DIO.GetIOInput(eDIName.L_PICK_BW) == false)
            {
                msg.AppendLine("* Left printer picker is not in reverse position.");
            }
            if (DIO.GetIOInput(eDIName.R_PICK_BW) == false)
            {
                msg.AppendLine("* Right printer picker is not in reverse position.");
            }

            if (AR.SETTING.Data.Enable_PickerCylinder)
            {
                if (DIO.GetIOInput(eDIName.L_CYLUP) == false)
                {
                    msg.AppendLine("* Left printer picker cylinder is not in UP position.");
                }
                if (DIO.GetIOInput(eDIName.R_CYLUP) == false)
                {
                    msg.AppendLine("* Right printer picker cylinder is not in UP position.");
                }
            }


            if (DIO.IsEmergencyOn() == true)
                msg.AppendLine("* Cannot move when in emergency stop state.");

            if (PUB.sm.Step == eSMStep.RUN)
                msg.AppendLine("* Cannot initialize while in operation");

            if (msg.Length > 0)
            {
                UTIL.MsgE(msg.ToString());
                return;
            }

            //CMenuButton btYes = new CMenuButton
            //{
            //    Text = "Initialize",
            //    Tag = "yes",
            //    BackColor = Color.Tomato,
            //    OverColor = Color.Gold
            //};

            //CMenuButton btNo = new CMenuButton("Cancel", "NO");
            //var menu = new CMenu("Do you want to execute motion home and status initialization?", "Device Initialization", "init", eMsgIcon.Alert, btYes, btNo);
            //loader1.AddMenu(menu);

            msg.Clear();
            msg.AppendLine("Execute motion home and status initialization?");
            var dlgresult = UTIL.MsgQ(msg.ToString());
            if (dlgresult != System.Windows.Forms.DialogResult.Yes) return;

            PUB.log.Add("User Click : initialize", false);
            Func_sw_initialize();
        }

        private void arLabel11_Click(object sender, EventArgs e)
        {
            if (PUB.sm.isRunning == true)
            {
                UTIL.MsgE("AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");
                return;
            }

            var popmsg = PUB.popup.Visible;
            using (fSetting f = new fSetting())
                if (f.ShowDialog() == DialogResult.OK)
                {
                    DIO.InitDIOSensitive();

                    //Pin definition file update
                    DIO.Pin.SetInputData(PUB.mdm.dataSet.InputDescription);
                    DIO.Pin.SetOutputData(PUB.mdm.dataSet.OutputDescription);

                    if (AR.SETTING.Data.Disable_RoomLight == true)
                        DIO.SetRoomLight(false);
                    if (AR.SETTING.Data.Disable_TowerLamp == true)
                    {
                        DIO.SetTwGrn(false);
                        DIO.SetTwRed(false);
                        DIO.SetTwYel(false);
                    }
                    if (AR.SETTING.Data.Serial_Remocon.isEmpty() == false)
                    {
                        var portinfo = AR.SETTING.Data.Serial_Remocon.Split(':');
                        var portName = portinfo[0];
                        int baud = 9600;
                        if (portinfo.Length > 1) baud = int.Parse(portinfo[1]);
                        if (PUB.remocon.PortName != portName)
                        {
                            PUB.remocon.Close();
                            PUB.remocon.PortName = portName;
                            PUB.remocon.BaudRate = baud;
                            if (PUB.remocon.Open() == false)
                                PUB.log.AddE("Remote Control Port Open Error : " + PUB.remocon.errorMessage);
                        }
                    }

                    groupBox3.Text = $"Model Info ({PUB.MCCode}/{AR.SETTING.Data.McName})";

                    //Printer setting - 201223
                    //PUB.PrinterL.printerName = COMM.SETTING.Data.PrintLeftName;
                    //PUB.PrinterR.printerName = COMM.SETTING.Data.PrintRightName;
                    UpdateControl();
                }
            if (popmsg) PUB.popup.Visible = true;
        }

        private void arLabel12_Click(object sender, EventArgs e)
        {

            string file = System.IO.Path.Combine(UTIL.CurrentPath, "Manual", "Manual.pdf");// "manual.pdf");
            if (System.IO.File.Exists(file) == false)
            {
                UTIL.MsgE("User manual file does not exist\n" +
                    "Contact : T8567 (Equipment Technology Team 1)\n" +
                    "File name : " + file);
                return;
            }
            UTIL.RunExplorer(file);
        }

        private void arLabel16_Click(object sender, EventArgs e)
        {

        }

        private void viewMapDataToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void openSaveFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void CaptureToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void btDebug_Click(object sender, EventArgs e)
        {
            arCtl.arLabel ctl = sender as arCtl.arLabel;
            this.cmDebug.Show(this, new Point(100, 100));
        }

        private void sMResetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PUB.sm.isRunning == true)
            {
                UTIL.MsgE("AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");
                return;
            }

            if (PUB.sm.Step != eSMStep.IDLE)
            {
                var dlg = UTIL.MsgQ(
                    "Initialize program status?\n\n" +
                    "All ongoing processes will be cancelled.\n" +
                    "[System initialization] may be required if necessary");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }
            else PUB.log.AddAT("Cannot initialize while in standby state");

            PUB.log.Add("User Click : initialize", false);
            PUB.sm.SetNewStep(eSMStep.IDLE, true);
            PUB.flag.set(eVarBool.FG_USERSTEP, false, "sMResetToolStripMenuItem_Click");
        }

        private void dIOMonitorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new fManualPrint0())
            {
                f.Text = "Barcode Process Test";
                if (f.ShowDialog() == DialogResult.OK)
                {
                    var reelinfo = f.reelinfo;
                    var vdata = new Class.JobData(9);
                    PUB.Result.ItemDataC.CopyTo(ref vdata);
                    vdata.Clear("TEST");
                    vdata.VisionData.BarcodeTouched = true;
                    if (reelinfo.SID.isEmpty() == false)
                    {
                        vdata.VisionData.SID = reelinfo.SID;
                        vdata.VisionData.SID_Trust = true;
                    }
                    if (reelinfo.venderLot.isEmpty() == false)
                    {
                        vdata.VisionData.VLOT = reelinfo.venderLot;
                        vdata.VisionData.VLOT_Trust = true;
                    }
                    if (reelinfo.id.isEmpty() == false)
                    {
                        vdata.VisionData.SetRID(reelinfo.id, "TEST");
                        vdata.VisionData.RID_Trust = true;
                    }
                    if (reelinfo.mfg.isEmpty() == false)
                    {
                        vdata.VisionData.MFGDATE = reelinfo.mfg;
                        vdata.VisionData.MFGDATE_Trust = true;
                    }
                    if (reelinfo.qty > 0)
                    {
                        vdata.VisionData.QTY = reelinfo.qty.ToString();
                        vdata.VisionData.QTY_Trust = true;
                    }
                    //vdata.VisionData.VLOT = reelinfo.venderLot;

                    BCDProcess_ALL(vdata, "TEST", true);
                    var msg = vdata.VisionData.ToString();
                    PUB.log.Add(msg);
                    UTIL.MsgE(msg);
                }
            }
        }

        private void refreshControklToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.hmi1.RemakeRect();
            UpdateControl();
            PUB.Result.DTSidConvertEmptyList.Clear();
            PUB.Result.DTSidConvertMultiList.Clear();
            PUB.Result.DTSidConvert.Clear();
            PUB.Result.DTSidConvert.AcceptChanges();
            if (PUB.Result.ItemDataC.VisionData != null)
                PUB.Result.ItemDataC.VisionData.barcodelist.Clear();
        }


        void loader1_IConClick(object sender, UIControl.HMI.IconClickEventargs e)
        {
            //throw new NotImplementedException();
            PUB.log.Add("Loader Icon Click : " + e.item.Tag.ToString());
            if (e.item.Tag == "air")
            {
                var buttonOk = new CMenuButton("ON", "1");
                var buttonNo = new CMenuButton("OFF", "0");
                var newmenu = new CMenu("Change AIR supply status", "AIR CONTROL", "air", eMsgIcon.Error, buttonOk, buttonNo)
                {
                    BorderColor = Color.Gray,
                };
                hmi1.AddMenu(newmenu);
            }

            else if (e.item.Tag == "emg")
            {
                btMReset.PerformClick();
            }

            else if (e.item.Tag == "debug")
            {
                PUB.flag.set(eVarBool.FG_DEBUG, !PUB.flag.get(eVarBool.FG_DEBUG), "");
                ShowDebugMenu();
            }
        }

        private void Loader1_ButtonClick(object sender, UIControl.HMI.MenuItemClickEventargs e)
        {
            //Button was pressed, so remove the corresponding menu
            PUB.log.Add("Menu Button Click : " + e.item.Tag);
            if (e.item.menutag == null)
            {
                //This is a regular button, not a menu
                if (e.item.Tag == "INPUTL")
                {

                }

                return;
            }
            else
            {
                switch (e.item.menutag)
                {
                    case "init":
                        if (e.item.Tag == "yes")
                        {
                            PUB.log.Add("User Click : initialize", false);
                            Func_sw_initialize();
                        }
                        break;
                    case "sample":
                        if (e.item.Tag == "1")
                            PUB.log.Add("ok button clicked");
                        else
                            PUB.log.Add("no button clicked");
                        break;

                    case "air":
                        if (e.item.Tag == "1")
                        {
                            DIO.SetAIR(true);
                            PUB.log.Add("User air on");
                        }
                        else
                        {
                            DIO.SetAIR(false);
                            PUB.log.Add("User air off");
                        }
                        break;
                }

            }

            //Remove the last menu
            hmi1.DelMenu();
        }

        private void sampleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var buttonOk = new CMenuButton("OK", "1");
            var buttonNo = new CMenuButton("CANCLE", "0");
            var newmenu = new CMenu("body str", "title", "sample", eMsgIcon.Error, buttonOk, buttonNo)
            {
                BorderColor = Color.Gray
            };
            hmi1.AddMenu(newmenu);
        }

        private void debugModeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.hmi1.arDebugMode = !this.hmi1.arDebugMode;
            this.hmi1.Invalidate();

        }



        private void countToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new Dialog.fDebug();
            f.TopMost = true;
            f.Show();
        }

        #region "System Parameter"

        #region "Motion Parameter"
        private void axis0ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.mot.ShowParameter(0);
        }

        private void axis1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.mot.ShowParameter(1);
        }

        private void axis2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.mot.ShowParameter(2);
        }

        private void axis3ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void axis4ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        #endregion

        private void clearToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            hmi1.ClearMenu();
        }

        #endregion

        private void processListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.log.Add("process list");
            foreach (var prc in System.Diagnostics.Process.GetProcesses())
            {
                if (prc.ProcessName.StartsWith("svchost")) continue;
                if (prc.ProcessName.Contains(".host")) continue;
                PUB.log.Add(prc.ProcessName);
            }
        }



        Control GetContextOwnerControl(object sender)
        {
            var menuitem = sender as ToolStripMenuItem;
            if (menuitem != null)
            {
                var menu = menuitem.Owner as ContextMenuStrip;
                if (menu != null)
                {
                    return menu.SourceControl;
                }
            }
            return null;
        }

        private void workSelectionScreenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new Dialog.fDataBufferSIDRef();
            f.TopMost = true;
            f.Show();
        }

        private void button3_Click_2(object sender, EventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

            if (PUB.flag.get(eVarBool.FG_DEBUG) == true)
            {
                PUB.flag.set(eVarBool.FG_DEBUG, false, "Under development");
            }
            else
            {
                PUB.flag.set(eVarBool.FG_DEBUG, true, "Under development");
            }

            ShowDebugMenu();

        }

        private void cmCam_Opening(object sender, CancelEventArgs e)
        {
            if (PUB.sm.Step < eSMStep.IDLE)
                cmCam.Enabled = false;
            else
                cmCam.Enabled = true;
        }



        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {

            var selectContorol = GetContextOwnerControl(sender);
            if (selectContorol == null) return;
            var selectedtag = selectContorol.Tag.ToString();
            var vidx = int.Parse(selectedtag);

            using (SaveFileDialog sd = new SaveFileDialog())
            {
                sd.Filter = "bitmap|*.bmp";
                sd.FileName = $"vision{vidx}.bmp";


                if (sd.ShowDialog() == DialogResult.OK)
                {
                    if (vidx == 1)
                    {
                        SaveImage(sd.FileName);
                    }
                }
            }

        }

        //private void sbVisTitle1_Click(object sender, EventArgs e)
        //{
        //	//Need to download from Keyence and process
        //	var tempfile = System.IO.Path.Combine(Util.CurrentPath, "Temp", "Keyence", DateTime.Now.ToString("HHmmss_fff") + ".bmp");
        //	var fi = new System.IO.FileInfo(tempfile);
        //	if (fi.Directory.Exists == false) fi.Directory.Create();
        //	this.iv1Keyence.DownloadRecentImage(fi.FullName);

        //}

        //private void livetaskToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //	//SetVisionTask();
        //	//PUB.flag.set(eVarBool.LIVIEWVIEW0, true, "");
        //}

        private void zoomFitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectContorol = GetContextOwnerControl(sender);
            if (selectContorol == null) return;
            var selectedtag = selectContorol.Tag.ToString();
            var vidx = int.Parse(selectedtag);
        }

        private void keyenceTrigOnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.keyenceF.Trigger(true); //Keyence_Trigger(true);
            PUB.keyenceR.Trigger(true); //Keyence_Trigger(true);

        }

        private void keyenceTrigOffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.keyenceF.Trigger(false); //Keyence_Trigger(false);
            PUB.keyenceR.Trigger(false); //Keyence_Trigger(false);
        }

        private void keyenceSaveImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fn = System.IO.Path.Combine(UTIL.CurrentPath, "Images", "keyence.bmp");
            SaveImage(fn);
        }

        void menu_barcodeconfirm()
        {
            //Save image
            if (PUB.sm.Step != eSMStep.RUN && PUB.sm.Step != eSMStep.PAUSE && PUB.sm.Step != eSMStep.WAITSTART)
            {
                var tempfilF = System.IO.Path.Combine(UTIL.CurrentPath, "Temp", "keyenceF.bmp");
                var tempfilR = System.IO.Path.Combine(UTIL.CurrentPath, "Temp", "keyenceR.bmp");

                var fiF = new System.IO.FileInfo(tempfilF);
                var fiR = new System.IO.FileInfo(tempfilR);

                if (fiF.Directory.Exists == false) fiF.Directory.Create();
                if (fiR.Directory.Exists == false) fiR.Directory.Create();

                var nimagF = PUB.keyenceF.SaveImage(fiF.FullName);
                var nimagR = false;

                if (PUB.keyenceR != null)
                    nimagR = PUB.keyenceR.SaveImage(fiR.FullName);
                ///this.pictureBox1.Image = nimag;

            
            }
            using (var f = new Dialog.fLoaderInfo(PUB.Result.ItemDataC.VisionData.bcdMessage))
                f.ShowDialog();
        }

        private void lbSize1_Click(object sender, EventArgs e)
        {

        }


        private void liveViewProcessOnOffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            liveviewprocesson = !liveviewprocesson;
        }

        private void lbLock2_Click(object sender, EventArgs e)
        {
            var ctl = sender as arCtl.arLabel;
            var index = int.Parse(ctl.Tag.ToString());
            //	bool cur = false;

            if (PUB.sm.isRunning)
            {
                UTIL.MsgE("Cannot perform cart exchange during operation\nPress 'STOP' button then try again");
                return;
            }

            bool curMag = DIO.GetIOOutput(eDOName.PORTL_MAGNET);
            bool curLim = DIO.GetIOInput(eDIName.PORTL_LIM_DN);
            if (index == 1)
            {
                curMag = DIO.GetIOOutput(eDOName.PORTC_MAGNET);
                curLim = DIO.GetIOInput(eDIName.PORTC_LIM_DN);
            }
            else if (index == 2)
            {
                curMag = DIO.GetIOOutput(eDOName.PORTR_MAGNET);
                curLim = DIO.GetIOInput(eDIName.PORTR_LIM_DN);
            }

            //		cur = Util_DO.GetIOOutput(eDOName.CART_MAG0);
            if (curMag == false)
            {
                PUB.log.Add($"MAGNET{index} ON by USER");
                DIO.SetPortMagnet(index, true); //Allow immediate turn on
            }
            else
            {
                if (curLim == false)
                {
                    UTIL.MsgE("Lower all ports then try again");
                    DIO.SetPortMotor(index, eMotDir.CCW, true, "Cart Exchange"); //Automatically lower the port
                    return;
                }
                DIO.SetPortMagnet(index, false);
                PUB.log.Add($"MAGNET{index} OFF by USER");
            }
        }

        private void arDatagridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //
        }

        private void arLabel6_Click(object sender, EventArgs e)
        {
            //Lower port
            if (PUB.sm.isRunning)
            {
                UTIL.MsgE("Cannot use during operation");
                return;
            }
            var index = int.Parse((sender as arCtl.arLabel).Tag.ToString());


            if (VAR.BOOL[eVarBool.Use_Conveyor] && (index == 0 || index == 2))
            {
                if (index == 0) DIO.SetOutput(eDOName.LEFT_CONV, true);
                if (index == 2) DIO.SetOutput(eDOName.RIGHT_CONV, true);
            }
            else
            {
                if (DIO.GetPortMotorRun(index) == true) DIO.SetPortMotor(index, eMotDir.CW, false, "UI");
                else
                {
                    if (UTIL.MsgQ("Lower the port?") == DialogResult.Yes)
                        DIO.SetPortMotor(index, eMotDir.CCW, true, "UI Port Lower");
                }
            }


        }

        private void arLabel11_Click_1(object sender, EventArgs e)
        {
            //Raise port
            if (PUB.sm.isRunning)
            {
                UTIL.MsgE("Cannot use during operation");
                return;
            }
            var index = int.Parse((sender as arCtl.arLabel).Tag.ToString());

            if (VAR.BOOL[eVarBool.Use_Conveyor] && (index == 0 || index == 2))
            {
                if (index == 0) DIO.SetOutput(eDOName.LEFT_CONV, false);
                if (index == 2) DIO.SetOutput(eDOName.RIGHT_CONV, false);
            }
            else
            {
                if (DIO.GetPortMotorRun(index) == true) DIO.SetPortMotor(index, eMotDir.CCW, false, "UI");
                else
                {
                    if (UTIL.MsgQ("Raise the port?") == DialogResult.Yes)
                        DIO.SetPortMotor(index, eMotDir.CW, true, "UI");
                }
            }


        }

        private void jObEndToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PUB.flag.get(eVarBool.FG_INIT_MOTIO) == false)
            {
                UTIL.MsgE("Motion not initialized\nPlease try again later");
                return;
            }
            ShowSummary();
        }

        private void button3_Click_4(object sender, EventArgs e)
        {

        }

        private void jOBStartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new Dialog.fSelectJob())
                f.ShowDialog();
        }



        private void button1_Click_1(object sender, EventArgs e)
        {

        }


        private void visionProcess0ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WS_Send(eWorkPort.Left, PUB.wsL, Guid.NewGuid().ToString(), "STATUS", "");
        }

        private void visionProcess1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WS_Send(eWorkPort.Right, PUB.wsR, Guid.NewGuid().ToString(), "STATUS", "");
        }

        private void customerRuleToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            menu_cancel();
        }

        private void toolStripButton15_Click(object sender, EventArgs e)
        {
            menu_barcodeconfirm();
        }

        private void btLogViewer_Click(object sender, EventArgs e)
        {
            var exename = UTIL.MakePath("LogView.exe");
            if (System.IO.File.Exists(exename) == false)
            {
                UTIL.MsgE($"Log viewer file not found\n{exename}\nPlease contact support (T8567)");
                return;
            }

            UTIL.RunProcess(exename);
        }

        private void toolStripButton16_Click(object sender, EventArgs e)
        {
            var file = UTIL.ScreenCapture(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height, new Point(0, 0), false);
            using (var f = new AR.Dialog.fMailReport("", file, "", AR.SETTING.Data.Bugreport_mail))
                f.ShowDialog();
        }

        async private void refreshToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            await RefreshList();
        }

        private void systemParameterMotorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frmSysMotParam == null || frmSysMotParam.IsDisposed || frmSysMotParam.Disposing)
            {
                if (frmSysMotParam != null) frmSysMotParam.FormClosed -= frmSysParam_FormClosed;
                frmSysMotParam = new Dialog.fSystem_MotParameter();
                frmSysMotParam.FormClosed += frmSysParam_FormClosed;
            }
            frmSysMotParam.Show();
            frmSysMotParam.Activate();
            if (frmSysMotParam.WindowState == FormWindowState.Minimized)
                frmSysMotParam.WindowState = FormWindowState.Normal;
        }

        private void speedLimitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AR.SETTING.Data.Enable_SpeedLimit = !AR.SETTING.Data.Enable_SpeedLimit;
        }

        private void triggerOnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.keyenceF.Trigger(true);
            PUB.keyenceR.Trigger(true);
        }

        private void triggerOffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.keyenceF.Trigger(false);
            PUB.keyenceR.Trigger(false);
        }


        private void quickExecutionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PUB.flag.get(eVarBool.FG_INIT_MOTIO) == false)
            {
                UTIL.MsgE("Motion not initialized\nPlease try again later");
                return;
            }
            if (PUB.sm.isRunning == true)
            {
                UTIL.MsgE("AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");
                return;
            }

            var f = new Dialog.Quick_Control();
            f.StartPosition = FormStartPosition.CenterScreen;
            f.Show();
        }

        async private void managementToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (PUB.sm.isRunning)
            {
                UTIL.MsgE("Cannot use during operation");
                return;
            }

            if (PUB.flag.get(eVarBool.FG_MOVE_PICKER))
            {
                UTIL.MsgE("The window is already open");
            }
            else
            {
                using (var f = new Dialog.fPickerMove())
                    f.ShowDialog();

                //If home position is not set and sensor is in center, ask for initialization
                if (PUB.mot.HasHomeSetOff == true && DIO.GetIOInput(eDIName.PICKER_SAFE))
                {
                    btMReset.PerformClick();
                }

                await RefreshList();
            }
        }

        private void regExTestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new Dialog.RegExTest())
                f.ShowDialog();
        }

        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            UTIL.RunExplorer(UTIL.CurrentPath);
        }

        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            PUB.LogFlush();
            var fi = new System.IO.FileInfo(PUB.log.FileName);
            UTIL.RunExplorer(fi.Directory.FullName);
        }

        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {
            string savefile = System.IO.Path.Combine(UTIL.CurrentPath, "ScreenShot", DateTime.Now.ToString("yyyyMMddHHmmss") + ".png");
            var grpath = new System.IO.FileInfo(savefile);
            UTIL.RunExplorer(grpath.Directory.FullName);
        }

        private void toolStripMenuItem15_Click(object sender, EventArgs e)
        {
            var basepath = AR.SETTING.Data.GetDataPath();
            var path = System.IO.Path.Combine(
                basepath, "History",
                DateTime.Now.Year.ToString("0000"),
                DateTime.Now.Month.ToString("00"),
                DateTime.Now.Day.ToString("00"));
            if (System.IO.Directory.Exists(path))
                UTIL.RunExplorer(path);
            else
                UTIL.RunExplorer(System.IO.Path.Combine(AR.SETTING.Data.GetDataPath(), "History"));
        }

        private void bcdRegProcessClearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lock (PUB.Result.BCDPatternLock)
            {
                PUB.Result.BCDPattern.Clear();
                PUB.Result.BCDIgnorePattern.Clear();
            }



            if (PUB.Result.ItemDataC.VisionData == null) return;


            lock (PUB.Result.ItemDataC.VisionData.barcodelist)
            {
                foreach (var item in PUB.Result.ItemDataC.VisionData.barcodelist)
                {
                    item.Value.RegExConfirm = false;
                }
            }
        }

        private void BarcodeRuleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new Dialog.RegExRule())
                f.ShowDialog();

            if (PUB.sm.Step != eSMStep.IDLE)
            {
                lock (PUB.Result.BCDPatternLock)
                {
                    var modelName = PUB.Result.vModel.Title;
                    PUB.Result.BCDPattern = PUB.GetPatterns(modelName, false);
                    PUB.Result.BCDIgnorePattern = PUB.GetPatterns(modelName, true);
                    PUB.log.Add($"Model pattern loading: {PUB.Result.BCDPattern.Count}/{PUB.Result.BCDIgnorePattern.Count}");
                }

            }
        }


        async private void ModelSelectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PUB.sm.isRunning == true)
            {
                UTIL.MsgE("AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");
                return;
            }

            using (var f = new Model_Operation())
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (SETTING.Data.SystemBypass)
                    {
                        UTIL.MsgI("BYPASS is enabled in settings\n" +
                            "Equipment will operate in BYPASS mode regardless of selected model\n" +
                            "[SYSTEM BYPASS]\n" +
                            "1. Camera function will be OFF\n" +
                            "2. Printer function will be OFF");
                    }
                    if (f.Value != "")
                    {
                        var ok = PUB.SelectModelV(f.Value);
                        var motionmode = VAR.BOOL[eVarBool.Use_Conveyor] ? "Conveyor" : "Default";
                        var changeMot = PUB.SelectModelM(motionmode);
                        if (changeMot == false)
                        {
                            PUB.log.AddE($"No Motion model (Conveyor)");
                        }
                        UpdateControl();
                    }
                }

        }

        private void displayVARToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new Dialog.fVAR();
            f.TopMost = true;
            f.Show();
        }

        private void lbMsg_Click(object sender, EventArgs e)
        {
            //reset function
            PUB.Result.ItemDataC.VisionData.Clear("USER UI CLICK", true);
            PUB.flag.set(eVarBool.FG_END_VISIONL, false, "USER UI CLICK");
        }



        private void toolStripMenuItem17_Click(object sender, EventArgs e)
        {
            //
            var curimageF = PUB.keyenceF.GetImage();
            PUB.keyenceF.UpdateBitmap((Bitmap)curimageF, (Bitmap)this.keyenceviewF.Image);

            var curimageR = PUB.keyenceR.GetImage();
            PUB.keyenceR.UpdateBitmap((Bitmap)curimageR, (Bitmap)this.keyenceviewR.Image);

        }

        private void triggerOnToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            PUB.keyenceF.Trigger(true);
            PUB.keyenceR.Trigger(true);
        }

        private void triggerOffToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            PUB.keyenceF.Trigger(false);
            PUB.keyenceR.Trigger(false);
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PUB.keyenceF != null)
            {
                PUB.keyenceF.Connect();
                PUB.flag.set(eVarBool.FG_KEYENCE_OFFF, false, "USER");
            }
            if (PUB.keyenceR != null)
            {
                PUB.keyenceR.Connect();
                PUB.flag.set(eVarBool.FG_KEYENCE_OFFR, false, "USER");
            }
        }

        private void disConnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PUB.keyenceF != null)
            {
                PUB.keyenceF.Disconnect();
                PUB.flag.set(eVarBool.FG_KEYENCE_OFFF, true, "USER");
            }
            if (PUB.keyenceR != null)
            {
                PUB.keyenceR.Disconnect();
                PUB.flag.set(eVarBool.FG_KEYENCE_OFFR, true, "USER");
            }
        }



        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PUB.keyenceF.Reset();
            PUB.keyenceR.Reset();
        }

        private void webManagerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UTIL.RunExplorer("http://" + AR.SETTING.Data.Keyence_IPF);
            UTIL.RunExplorer("http://" + AR.SETTING.Data.Keyence_IPR);
        }

        private void toolStripMenuItem23_Click(object sender, EventArgs e)
        {
            if (PUB.flag.get(eVarBool.FG_INIT_MOTIO) == false)
            {
                UTIL.MsgE("Motion not initialized\nPlease try again later");
                return;
            }

            if (PUB.sm.isRunning == true)
            {
                UTIL.MsgE("AUTO-RUN MODE\\nCannot be used during automatic execution\\nPlease stop and try again");
                return;
            }

            using (var f = new Model_Motion())
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (f.Value != "")
                    {
                        PUB.SelectModelM(f.Value);
                    }
                }
        }

        private void motionEmulatorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            needShowSummary = true;
        }

        private void ConnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PUB.wsL != null && PUB.wsL.Connected)
            {
                UTIL.MsgI("Program is currently connected");
                return;
            }

            //camera execution
            if (AR.SETTING.Data.CameraLFile.isEmpty() == true)
            {
                UTIL.MsgE("Barcode program filename not specified", true);
                return;
            }

            var fi = new System.IO.FileInfo(AR.SETTING.Data.CameraLFile);
            if (fi.Exists == false)
            {
                UTIL.MsgE("Vision program file does not exist\n" + fi.FullName);
                return;
            }

            //var prc = null;// Util.CheckExistProcess("CrevisQRCode");
            //if (prc == null)
            {
                //Util.MsgI("Barcode program has been launched\nIt will run after a moment");
                UTIL.RunProcess(fi.FullName);
            }
            //else
            //{

            //	SetActiveWindow((int)prc.MainWindowHandle);
            //	SetForegroundWindow(prc.MainWindowHandle);
            //	ShowWindow(prc.MainWindowHandle, (int)CmdShow.Normal);
            //}
        }


        private void toolStripMenuItem21_Click(object sender, EventArgs e)
        {
            PUB.flag.set(eVarBool.FG_PRC_VISIONL, true, "USER");
            PUB.flag.set(eVarBool.FG_END_VISIONL, false, "USER");
            WS_Send(eWorkPort.Left, PUB.wsL, PUB.Result.ItemDataL.guid, "TRIG", PUB.Result.ItemDataL.VisionData.PrintQRData);
        }

        private void toolStripMenuItem24_Click(object sender, EventArgs e)
        {
            WS_Send(eWorkPort.Left, PUB.wsL, string.Empty, "OFF", string.Empty);
        }

        private void postDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new Dialog.Debug.fSendInboutData())
                f.ShowDialog();
        }

        private void manualPrintToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new Dialog.fManualPrint0())
                if (f.ShowDialog() == DialogResult.OK)
                {
                    var rlt = PUB.PrinterR.Print(f.reelinfo, true, false);
                    PUB.log.Add($"manual print:{PUB.PrinterR.qrData}");
                }
        }

        private void arDatagridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void toolStripButton6_ButtonClick(object sender, EventArgs e)
        {
            if (PUB.flag.get(eVarBool.FG_INIT_MOTIO) == false)
            {
                UTIL.MsgE("Motion not initialized\nPlease try again later");
                return;
            }
            //show io panerl
            using (var f = new Dialog.fIOMonitor())
                f.ShowDialog();
        }


        private void apiCheckToolStripMenuItem_Click(object sender, EventArgs e)
        {

            PUB.UpdateSIDInfo().Wait();

        }

        private void barcodeTestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var bcd = "21PMULTILAYER CHIP INDUCTORS,P110-50933-01R5,1T5015326894,1J083476968109,16D20230908,14D20250821,Q20000,1PMHQ0402PSA1N5BT000";
            //var d = UTIL.InputBox("barcode input", bcd);

            PUB.Result.ItemDataC.VisionData.barcodelist.Clear();
            PUB.Result.ItemDataC.VisionData.barcodelist.TryAdd(bcd, new Class.KeyenceBarcodeData
            {
                barcodeSymbol = "2",
                Data = bcd,
            });
            //BarcodeFix_ReceiveData(null, new arDev.RS232.ReceiveDataEventArgs(System.Text.Encoding.Default.GetBytes(d.Item2)));
        }

        private void toolStripMenuItem28_Click(object sender, EventArgs e)
        {
            PUB.flag.set(eVarBool.FG_PRC_VISIONR, true, "USER");
            PUB.flag.set(eVarBool.FG_END_VISIONR, false, "USER");
            WS_Send(eWorkPort.Right, PUB.wsR, PUB.Result.ItemDataR.guid, "TRIG", PUB.Result.ItemDataR.VisionData.PrintQRData);
        }

        private void toolStripMenuItem30_Click(object sender, EventArgs e)
        {
            WS_Send(eWorkPort.Right, PUB.wsR, string.Empty, "OFF", string.Empty);
        }

        private void OpenProgramToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fn = AR.SETTING.Data.Sidinfofilename;
            var fi = new System.IO.FileInfo(fn);
            if (fi.Exists == false)
            {
                PUB.log.AddE($"No  Sid info  file:{fn}");
                return; ;
            }

            //var file = @"d:\amkor\sidinfo\update.exe " + COMM.SETTING.Data.McName;// System.IO.Path.Combine(Util.CurrentPath, "Module", "SidInfo", "amkor.exe");
            UTIL.RunProcess(fi.FullName);
        }

        async private void InboundDataUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var rlt = await PUB.UpdateSIDInfo();
            if (rlt.Item1 == false)
            {
                PUB.log.AddE($"SID Information update failed: " + rlt.Item2);
            }
            else PUB.log.AddI($"SID Information update successful");
        }

        private void hmi1_ZoneItemClick(object sender, HMI.ZoneItemClickEventargs e)
        {
            var buttontag = e.item.Tag;
            var buttonidx = e.item.index;

            //In conveyor mode, buffer is initialized when clicked.
            var cv = VAR.BOOL[eVarBool.Use_Conveyor];
            if (cv && buttontag.StartsWith("PORT"))
            {
                //Remove buffer quantity when clicked
                if (buttonidx == 0) VAR.I32[eVarInt32.LEFT_ITEM_COUNT] = 0;
                else if (buttonidx == 2) VAR.I32[eVarInt32.RIGT_ITEM_COUNT] = 0;
                PUB.log.AddAT($"User buffer removed {buttontag}:{buttonidx}");
            }

        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            using (var f = new Dialog.fManualPrint())
                f.ShowDialog();
        }

        private void multiSIDSelectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //select columns
            List<string> fields = new List<string>();
            VAR.STR[eVarString.JOB_CUSTOMER_CODE] = "0000000001";
            var vCustCode = VAR.STR[eVarString.JOB_CUSTOMER_CODE];
            var vPartNo = "";
            var vVname = "";
            var vSID = "";
            var vBatch = "";
            var vLot = "";
            var vMFG = "";

            if (PUB.Result.ItemDataC.VisionData.VLOT.isEmpty()) PUB.Result.ItemDataC.VisionData.VLOT = "4CB24QK1G";
            if (PUB.Result.ItemDataC.VisionData.MFGDATE.isEmpty()) PUB.Result.ItemDataC.VisionData.MFGDATE = "2501";
            if (PUB.Result.ItemDataC.VisionData.PARTNO.isEmpty()) PUB.Result.ItemDataC.VisionData.PARTNO = "parno";
            if (PUB.Result.ItemDataC.VisionData.QTY.isEmpty()) PUB.Result.ItemDataC.VisionData.QTY = "1000";


            using (var f = new Dialog.fManualPrint0(
                fManualPrint0.eOpt.sid | fManualPrint0.eOpt.vlot | fManualPrint0.eOpt.partno | fManualPrint0.eOpt.vname))
            {
                f.Text = "Input Data";
                if (f.ShowDialog() != DialogResult.OK) return;
                vPartNo = f.reelinfo.PartNo;
                vVname = f.reelinfo.venderName;
                vSID = f.reelinfo.SID;
                vLot = f.reelinfo.venderLot;
                vMFG = f.reelinfo.mfg;
            }

            if (VAR.BOOL[eVarBool.Opt_SID_Apply_CustCode]) fields.Add("CUST_CODE");
            if (VAR.BOOL[eVarBool.Opt_SID_Apply_PartNo]) fields.Add("PART_NO");
            if (VAR.BOOL[eVarBool.Opt_SID_Apply_VenderName]) fields.Add("VENDOR_NM");
            if (VAR.BOOL[eVarBool.Opt_SID_Apply_SID]) fields.Add("SID");
            if (VAR.BOOL[eVarBool.Opt_SID_Apply_batch]) fields.Add("BATCH_NO"); //220921

            //where coluns
            var Apply = true;
            List<string> wheres = new List<string>();
            if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_CustCode])
            {
                if (vCustCode.isEmpty() == false) wheres.Add($"CUST_CODE='{vCustCode}'");
                else Apply = false;
            }
            if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_PartNo])
            {
                if (vPartNo.isEmpty() == false) wheres.Add($"PART_NO='{vPartNo}'");
                else Apply = false;
            }
            if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_SID])
            {
                if (vSID.isEmpty() == false) wheres.Add($"SID='{vSID}'");
                else Apply = false;
            }
            if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_VLOT])  //221013
            {
                if (vLot.isEmpty() == false) wheres.Add($"VENDOR_LOT = '{vLot}'");
                else Apply = false;
            }

            if (Apply == false)
            {
                UTIL.MsgE("Cannot proceed as condition data is not met");
                return;
            }
            if (fields.Any() == false)
            {
                UTIL.MsgE("Update column does not exist");
                return;
            }
            if (wheres.Any() == false)
            {
                UTIL.MsgE("Condition column does not exist");
                return;
            }

            //if query data . no error
            var mcname = VAR.BOOL[eVarBool.Use_Conveyor] ? PUB.MCCode : SETTING.Data.McName;

            var TableName = "VW_GET_MAX_QTY_VENDOR_LOT";
            var whereState = " where " + string.Join(" and ", wheres);
            var selectFields = string.Join(",", fields);

            var SQL = $"select top 1 {selectFields} from {TableName} WITH(NOLOCK) {whereState}";
            var SQLC = $"select count(*)  from {TableName} WITH(NOLOCK) {whereState}";

            //If multiple information exists, it should be handled with selection screen

            VAR.STR[eVarString.MULTISID_QUERY] = $"select * from {TableName} WITH(NOLOCK) {whereState}";
            VAR.STR[eVarString.MULTISID_FIELDS] = selectFields;

            PUB.Result.ItemDataC.VisionData.CUSTCODE = VAR.STR[eVarString.JOB_CUSTOMER_CODE];
            using (var f = new fSelectSIDInformation())
                if (f.ShowDialog() == DialogResult.OK)
                {

                }
        }

        private void toolStripMenuItem27_Click(object sender, EventArgs e)
        {
            var bt = sender as ToolStripMenuItem;
            var txt = bt.Text;
            if (int.TryParse(txt, out int memno) == false)
            {
                UTIL.MsgE($"Keyence MemoryNo Error : {txt}");
                return;
            }
            PUB.log.Add($"Keyence Send BLOAD({memno})");
            if (PUB.keyenceF != null) PUB.keyenceF.BLoad(memno);
            if (PUB.keyenceR != null) PUB.keyenceR.BLoad(memno);
        }

        private void btAutoReelOut_Click(object sender, EventArgs e)
        {
            PUB.Result.AutoReelOut = !PUB.Result.AutoReelOut;
        }

        private void tbBarcodeR_Click(object sender, EventArgs e)
        {
            var lb = sender as arCtl.arLabel;
            if (lb == null) return;
            var txt = lb.Text.Trim();
            if(txt.isEmpty()==false)
            {
                Clipboard.SetText(txt);
                PUB.log.AddI($"Clipboard copy : {txt}");
            }
        }
    }
}