using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AR;

namespace Project.Dialog
{
    public partial class Quick_Control : Form
    {
        public Quick_Control()
        {
            InitializeComponent();
            this.FormClosing += __Closing;
            //this.lbTitle.MouseMove += LbTitle_MouseMove;
            //this.lbTitle.MouseUp += LbTitle_MouseUp;
            //this.lbTitle.MouseDown += LbTitle_MouseDown;
        }

        void __Closing(object sender, FormClosingEventArgs e)
        {
            timer1.Stop();
        }
        private void __LoaD(object sender, EventArgs e)
        {
            timer1.Start();
            //button31.Text = ((eAxis)0).ToString();
            //button32.Text = ((eAxis)1).ToString();
            //button33.Text = ((eAxis)2).ToString();
        }
        #region "Mouse Form Move"

        private Boolean fMove = false;
        private Point MDownPos;
        private void LbTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (fMove)
            {
                Point offset = new Point(e.X - MDownPos.X, e.Y - MDownPos.Y);
                this.Left += offset.X;
                this.Top += offset.Y;
                offset = new Point(0, 0);
            }
        }
        private void LbTitle_MouseUp(object sender, MouseEventArgs e)
        {
            fMove = false;
        }
        private void LbTitle_MouseDown(object sender, MouseEventArgs e)
        {
            MDownPos = new Point(e.X, e.Y);
            fMove = true;
        }

        #endregion
        private void button1_Click(object sender, EventArgs e)
        {
            if (PUB.mot.IsHomeSet((int)eAxis.Z_THETA) == false)
            {
                UTIL.MsgE("Cannot move because home search is not completed");
                return;
            }

            var speed = 50.0;
            if (PUB.Result != null &&
                PUB.Result.mModel != null &&
                PUB.Result.mModel.Title != "")
                speed = 0;// Pub.Result.mModel.XSpeed;

            MOT.Move(eAxis.Z_THETA, 0, speed);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //감지센서 상태 210208
            button5.BackColor = DIO.GetIOInput(eDIName.L_PICK_VAC) ? Color.Lime : Color.FromArgb(70, 70, 70);
            button5.ForeColor = DIO.GetIOInput(eDIName.L_PICK_VAC) ? Color.Black : Color.White;

            button6.BackColor = DIO.GetIOInput(eDIName.R_PICK_VAC) ? Color.Lime : Color.FromArgb(70, 70, 70);
            button6.ForeColor = DIO.GetIOInput(eDIName.R_PICK_VAC) ? Color.Black : Color.White;


            btLCyl.BackColor = DIO.GetIOOutput(eDOName.L_CYLDN) ? Color.Black : Color.White;
            btRCyl.BackColor = DIO.GetIOOutput(eDOName.R_CYLDN) ? Color.Black : Color.White;



            //메세지업데이트  230830
            var lcylup = DIO.GetIOInput(eDIName.L_CYLUP);
            var lcyldn = DIO.GetIOInput(eDIName.L_CYLDN);
            var rcylup = DIO.GetIOInput(eDIName.R_CYLUP);
            var rcyldn = DIO.GetIOInput(eDIName.R_CYLDN);
            btLCyl.Text = "L Cylinder\n" + (lcylup ? "(UP)" : (lcyldn ? "(DN)" : "--"));
            btRCyl.Text = "R Cylinder\n" + (rcylup ? "(UP)" : (rcyldn ? "(DN)" : "--"));

            var Lconv = DIO.GetIOOutput(eDOName.LEFT_CONV);
            var Rconv = DIO.GetIOOutput(eDOName.RIGHT_CONV);
            button17.Text = "L Conveyor\n" + (Lconv ? "(RUN)" : "(STOP)");
            button19.Text = "R Conveyor\n" + (Rconv ? "(RUN)" : "(STOP)");
            button17.BackColor = Lconv ? Color.Lime : Color.White;
            button19.BackColor = Rconv ? Color.Lime : Color.White;


        }

        private void button20_Click_1(object sender, EventArgs e)
        {
            //button zero
            var but = sender as Button;
            var motidx = short.Parse(but.Tag.ToString());
            var axis = (eAxis)motidx;

            //전체 이동경로상 오류가 있으면 처리 하지 않는다.
            var ermsg = new System.Text.StringBuilder();

            if (PUB.mot.IsHomeSet((short)axis) == false)
            {
                ermsg.AppendLine("Home search is not completed for this axis");
            }


            if (ermsg.Length > 0)
            {
                UTIL.MsgE("Cannot move\n" + ermsg.ToString());
                return;
            }


            var dlg = UTIL.MsgQ(string.Format("Do you want to move motion axis ({0}) to position 0?\n" +
                "Position 0 is generally the home position", axis));
            if (dlg != DialogResult.Yes) return;
            PUB.log.Add("user:move to zero axis=" + axis.ToString());
            PUB.mot.Move(motidx, 0);
        }

        private void button16_Click_1(object sender, EventArgs e)
        {
            //button stop
            var but = sender as Button;
            var motidx = short.Parse(but.Tag.ToString());
            var axis = (eAxis)motidx;

            //var dlg = Util.MsgQ("모션 {0}({1}) 을 위치 '0'으로 이동 할까요?\n" +
            //    "경로 상 충돌가능성을 확인 한 후 실행하세요");
            //if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            PUB.log.Add("user:motion stop axis=" + axis.ToString());
            PUB.mot.MoveStop("user stop", motidx);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //ccw
            var but = sender as Button;
            var motidx = short.Parse(but.Tag.ToString());
            var axis = (eAxis)motidx;
            PUB.log.Add("user:motion move -3.0 axis=" + axis.ToString());
            PUB.mot.Move(motidx, -3.0, true);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //cw
            var but = sender as Button;
            var motidx = short.Parse(but.Tag.ToString());
            var axis = (eAxis)motidx;
            PUB.log.Add("user:motion move +3.0 axis=" + axis.ToString());
            PUB.mot.Move(motidx, 3.0, true);
        }

        private void button40_Click(object sender, EventArgs e)
        {
            var but = sender as Button;
            var butindex = int.Parse(but.Tag.ToString());
            DIO.SetPortMotor(butindex, eMotDir.CW, true, "UC");
        }

        private void tbClose_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button10_Click_1(object sender, EventArgs e)
        {
            var but = sender as Button;
            var butindex = int.Parse(but.Tag.ToString());
            DIO.SetPortMotor(butindex, eMotDir.CCW, true, "UC");
        }

        private void button13_Click_2(object sender, EventArgs e)
        {
            var but = sender as Button;
            var butindex = int.Parse(but.Tag.ToString());
            DIO.SetPortMotor(butindex, eMotDir.CCW, false, "UC");
        }

        private void button41_Click(object sender, EventArgs e)
        {
            //front
            var cur = DIO.GetIOOutput(eDOName.PICK_VAC1);
            DIO.SetPickerVac(!cur, true);
        }

        private void button39_Click(object sender, EventArgs e)
        {

        }

        private void button44_Click(object sender, EventArgs e)
        {
            var cur = DIO.GetIOOutput(eDOName.SOL_AIR);
            DIO.SetAIR(!cur);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            var but = sender as Button;
            var butindex = int.Parse(but.Tag.ToString());
            Boolean current = false;

            if (butindex == 0) current = DIO.GetIOOutput(eDOName.PORTL_MAGNET);
            else if (butindex == 1) current = DIO.GetIOOutput(eDOName.PORTC_MAGNET);
            else current = DIO.GetIOOutput(eDOName.PORTR_MAGNET);

            DIO.SetPortMagnet(butindex, !current);
        }

        private void button51_Click(object sender, EventArgs e)
        {
            var but = sender as Button;
            var tagstr = but.Tag.ToString();
            if (tagstr == "1")
            {
                if (DIO.GetIOOutput(eDOName.PRINTL_VACI) == true)
                    DIO.SetPrintLVac(ePrintVac.off, true);
                else
                    DIO.SetPrintLVac(ePrintVac.inhalation, true);
            }
            else if (tagstr == "2")
                if (DIO.GetIOOutput(eDOName.PRINTL_VACO) == true)
                    DIO.SetPrintLVac(ePrintVac.off, true);
                else
                    DIO.SetPrintLVac(ePrintVac.exhaust, true);
            else
                DIO.SetPrintLVac(ePrintVac.off, true);
        }



        private void button53_Click(object sender, EventArgs e)
        {
            var but = sender as Button;
            var tagstr = but.Tag.ToString();
            if (tagstr == "1")
            {
                if (DIO.GetIOOutput(eDOName.PRINTR_VACI) == true)
                    DIO.SetPrintRVac(ePrintVac.off, true);
                else
                    DIO.SetPrintRVac(ePrintVac.inhalation, true);
            }
            else if (tagstr == "2")
                if (DIO.GetIOOutput(eDOName.PRINTR_VACO) == true)
                    DIO.SetPrintRVac(ePrintVac.off, true);
                else
                    DIO.SetPrintRVac(ePrintVac.exhaust, true);
            else
                DIO.SetPrintRVac(ePrintVac.off, true);
        }

        private void button57_Click(object sender, EventArgs e)
        {
            //바닥바람
            var curvalu = DIO.GetIOOutput(eDOName.PRINTL_AIRON);
            DIO.SetOutput(eDOName.PRINTL_AIRON, !curvalu);
        }

        private void button58_Click(object sender, EventArgs e)
        {
            //바닥바람
            var curvalu = DIO.GetIOOutput(eDOName.PRINTR_AIRON);
            DIO.SetOutput(eDOName.PRINTR_AIRON, !curvalu);
        }

        private void button60_Click(object sender, EventArgs e)
        {
            var cur = DIO.GetIOOutput(eDOName.PRINTL_FWD);
            if (cur == false)
            {
                var dlg = UTIL.MsgQ("Do you want to advance the printer (left) picker?");   //210209
                if (dlg != DialogResult.Yes) return;

                //준비위치에서는 전진하면 충돌한다
                var ReadyPos = MOT.GetLMPos(eLMLoc.READY);
                if (MOT.getPositionMatch(ReadyPos))
                {
                    if (UTIL.MsgQ("There is a risk of collision at the current position. Do you want to proceed anyway?") != DialogResult.Yes)
                        return;
                }
            }

            DIO.SetOutput(eDOName.PRINTL_FWD, !cur);
        }

        private void button59_Click(object sender, EventArgs e)
        {
            var cur = DIO.GetIOOutput(eDOName.PRINTR_FWD);
            if (cur == false)
            {
                var dlg = UTIL.MsgQ("Do you want to advance the printer (right) picker?");
                if (dlg != DialogResult.Yes) return;

                //준비위치에서는 전진하면 충돌한다
                var ReadyPos = MOT.GetRMPos(eRMLoc.READY);
                if (MOT.getPositionMatch(ReadyPos))
                {
                    if (UTIL.MsgQ("There is a risk of collision at the current position. Do you want to proceed anyway?") != DialogResult.Yes)
                        return;
                }
            }
            DIO.SetOutput(eDOName.PRINTR_FWD, !cur);
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            var rlt = PUB.PrinterL.TestPrint(AR.SETTING.Data.DrawOutbox, "ATK4EE1", "");
            var zpl = PUB.PrinterL.LastPrintZPL;
            if (rlt.result == false)
                PUB.log.AddE($"Temp Print L: {rlt.errmessage}" + PUB.PrinterL.LastPrintZPL);
            else
                PUB.log.Add("Temp Print L: " + PUB.PrinterL.LastPrintZPL);
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            var rlt = PUB.PrinterR.TestPrint(AR.SETTING.Data.DrawOutbox, "ATK4EE1", "");
            var zpl = PUB.PrinterR.LastPrintZPL;
            if (rlt.result == false)
                PUB.log.AddE($"Temp Print R: {rlt.errmessage}" + PUB.PrinterR.LastPrintZPL);
            else
                PUB.log.Add("Temp Print R: " + PUB.PrinterR.LastPrintZPL);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            //왼쪽검증취소
            if (PUB.flag.get(eVarBool.FG_PRC_VISIONL) == false) return;
            var dlg = UTIL.MsgQ("Do you want to cancel LEFT-QR code verification?");
            if (dlg != DialogResult.Yes) return;

            PUB.flag.set(eVarBool.FG_PRC_VISIONL, false, "CANCEL");
            PUB.flag.set(eVarBool.FG_PORTL_ITEMON, false, "CANCEL");
            PUB.flag.set(eVarBool.FG_END_VISIONL, false, "CANCEL");

            /// PUB.sm.seq.Clear(eSMStep.RUN_VISION0);
            //PUB.sm.seq.UpdateTime(eSMStep.RUN_COM_VS0);
            PUB.log.Add(string.Format("LEFT-QR verification ({0}) cancelled JGUID={1}", "L", PUB.Result.ItemDataL.guid));
        }

        private void button16_Click(object sender, EventArgs e)
        {
            if (PUB.flag.get(eVarBool.FG_PRC_VISIONR) == false) return;
            var dlg = UTIL.MsgQ("Do you want to cancel RIGHT-QR code verification?");
            if (dlg != DialogResult.Yes) return;

            PUB.flag.set(eVarBool.FG_PRC_VISIONR, false, "CANCEL");
            PUB.flag.set(eVarBool.FG_PORTR_ITEMON, false, "CANCEL");
            PUB.flag.set(eVarBool.FG_END_VISIONR, false, "CANCEL");

            //PUB.sm.seq.Clear(eSMStep.RUN_VISION2);
            //PUB.sm.seq.UpdateTime(eSMStep.RUN_COM_VS2);
            PUB.log.Add(string.Format("RIGHT-QR verification ({0}) cancelled JGUID={1}", "R", PUB.Result.ItemDataR.guid));
        }

        private void button8_Click(object sender, EventArgs e)
        {
            //왼쪽 -5mm
            var pos = MOT.GetLMPos(eLMLoc.READY);
            MOT.Move(eAxis.PL_MOVE, -5, 100, 500, true, false, false);//, vel, acc, false, false, false);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            //왼쪽 Ready Position
            var pos = MOT.GetLMPos(eLMLoc.READY);
            MOT.Move(eAxis.PL_MOVE, pos.Position, 50, 200, false, false, false);
            PUB.log.Add("user:PL_MOVE:to ready");
        }

        private void button15_Click_1(object sender, EventArgs e)
        {
            //오른쪽 -5mm
            var pos = MOT.GetRMPos(eRMLoc.READY);
            MOT.Move(eAxis.PR_MOVE, -5, 100, 500, false, false, false);// pos.Position + AR.SETTING.Data.MoveYForPaperVaccumeValue, vel, acc, false, false, false);
        }

        private void button16_Click_2(object sender, EventArgs e)
        {
            //오른쪽 Ready Position
            var pos = MOT.GetRMPos(eRMLoc.READY);
            MOT.Move(eAxis.PR_MOVE, pos.Position, 50, 200, false, false, false);
            PUB.log.Add("user:pr_move:to ready");
        }

        private void button17_Click(object sender, EventArgs e)
        {
            var cur = DIO.GetIOOutput(eDOName.LEFT_CONV);
            DIO.SetOutput(eDOName.LEFT_CONV, !cur);
        }

        private void button19_Click(object sender, EventArgs e)
        {
            var cur = DIO.GetIOOutput(eDOName.RIGHT_CONV);
            DIO.SetOutput(eDOName.RIGHT_CONV, !cur);
        }

        private void button20_Click(object sender, EventArgs e)
        {
            var cur = DIO.GetIOOutput(eDOName.L_CYLDN);
            if (cur == false)
            {
                //내려도되는지 검사해야한다.
                if (PUB.mot.IsHomeSet((int)eAxis.PL_MOVE))
                {
                    var pos = MOT.GetLMPos(eLMLoc.READY);
                    if (MOT.getPositionMatch(pos))
                    {
                        PUB.log.AddE($"Cannot lower cylinder (L) because it is at standby position");
                    }
                }
            }
            DIO.SetOutput(eDOName.L_CYLDN, !cur);
        }

        private void button21_Click(object sender, EventArgs e)
        {
            var cur = DIO.GetIOOutput(eDOName.R_CYLDN);
            if (cur == false)
            {
                //내려도되는지 검사해야한다.
                if (PUB.mot.IsHomeSet((int)eAxis.PR_MOVE))
                {
                    var pos = MOT.GetRMPos(eRMLoc.READY);
                    if (MOT.getPositionMatch(pos))
                    {
                        PUB.log.AddE($"Cannot lower cylinder (R) because it is at standby position");
                    }
                }
            }
            DIO.SetOutput(eDOName.R_CYLDN, !cur);
        }
    }
}
