using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using AR;
namespace Project.Dialog
{
    public partial class fPickerMove : Form
    {
        public fPickerMove()
        {
            InitializeComponent();
            this.FormClosing += FPickerMove_FormClosing;
        }
        private void fPickerMove_Load(object sender, EventArgs e)
        {
            PUB.flag.set(eVarBool.FG_MOVE_PICKER, true, "PICKERMOVE");
            timer1.Start();
        }
        private void FPickerMove_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ManPosL)
            {
                UTIL.MsgE("Printer motion is in management position\nReturn to position and try again", true);
                e.Cancel = true;
                return;
            }
            if (ManPosR)
            {
                UTIL.MsgE("Printer motion is in management position\nReturn to position and try again", true);
                e.Cancel = true;
                return;
            }
            PUB.flag.set(eVarBool.FG_MOVE_PICKER, false, "PICKERMOVE");
            timer1.Stop();
        }

        Boolean CheckSafty()
        {
            if (DIO.isSaftyDoorF() == false)
            {
                UTIL.MsgE("Front door is open");
                return false;
            }

            if (PUB.mot.HasHomeSetOff)
            {
                UTIL.MsgE("Motion home operation is not completed");
                return false;
            }
            return true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (CheckSafty() == false) return;

            //Z-check
            var z = MOT.GetPZPos(ePZLoc.READY);
            var zpos = MOT.getPositionOffset(z);
            if (zpos >= 0.5)
            {
                UTIL.MsgE("Raise the Z axis and try again");
                return;
            }

            //왼쪽프린터 뭉치가 준비위치가 아니면 오류
            var m1 = MOT.GetLMPos(eLMLoc.READY);
            if (MOT.getPositionMatch(m1) == false)
            {
                UTIL.MsgE("Printer attachment is not in ready position.\nCannot move as collision may occur");
                return;
            }


            //도어가 열려있다면 경고메세지를 표시한다.
            if (DIO.isSaftyDoorF(2, true) == false)
            {
                if (UTIL.MsgQ("Door is open. Do you want to move the motion?") != DialogResult.Yes) return;
            }


            var p1 = MOT.GetPXPos(ePXLoc.PICKOFFL);
            MOT.Move(eAxis.PX_PICK, p1.Position, 250, p1.Acc, false, false, false);
            DialogResult = DialogResult.OK;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (CheckSafty() == false) return;

            //Z-check
            var z = MOT.GetPZPos(ePZLoc.READY);
            var zpos = MOT.getPositionOffset(z);
            if (zpos >= 0.5)
            {
                UTIL.MsgE("Raise the Z axis and try again");
                return;
            }

            //왼쪽프린터 뭉치가 준비위치가 아니면 오류
            var m1 = MOT.GetLMPos(eLMLoc.READY);
            if (MOT.getPositionMatch(m1) == false)
            {
                UTIL.MsgE("Printer attachment is not in ready position.\nCannot move as collision may occur");
                return;
            }

            //도어가 열려있다면 경고메세지를 표시한다.
            if (DIO.isSaftyDoorF(2, true) == false)
            {
                if (UTIL.MsgQ("Door is open. Do you want to move the motion?") != DialogResult.Yes) return;
            }

            var p1 = MOT.GetPXPos(ePXLoc.READYL);
            MOT.Move(eAxis.PX_PICK, p1.Position, 250, p1.Acc, false, false, false);
            DialogResult = DialogResult.OK;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (CheckSafty() == false) return;

            //Z-check
            var z = MOT.GetPZPos(ePZLoc.READY);
            var zpos = MOT.getPositionOffset(z);
            if (zpos >= 0.5)
            {
                UTIL.MsgE("Raise the Z axis and try again");
                return;
            }

            //도어가 열려있다면 경고메세지를 표시한다.
            if (DIO.isSaftyDoorF(1, true) == false)
            {
                if (UTIL.MsgQ("Door is open. Do you want to move the motion?") != DialogResult.Yes) return;
            }

            var p1 = MOT.GetPXPos(ePXLoc.PICKON);
            MOT.Move(eAxis.PX_PICK, p1.Position, 250, p1.Acc, false, false, false);
            DialogResult = DialogResult.OK;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (CheckSafty() == false) return;

            //Z-check
            var z = MOT.GetPZPos(ePZLoc.READY);
            var zpos = MOT.getPositionOffset(z);
            if (zpos >= 0.5)
            {
                UTIL.MsgE("Raise the Z axis and try again");
                return;
            }

            //오른쪽프린터 뭉치가 준비위치가 아니면 오류
            var m1 = MOT.GetRMPos(eRMLoc.READY);
            if (MOT.getPositionMatch(m1) == false)
            {
                UTIL.MsgE("Printer attachment is not in ready position.\nCannot move as collision may occur");
                return;
            }
            //도어가 열려있다면 경고메세지를 표시한다.
            if (DIO.isSaftyDoorF(0, true) == false)
            {
                if (UTIL.MsgQ("Door is open. Do you want to move the motion?") != DialogResult.Yes) return;
            }
            var p1 = MOT.GetPXPos(ePXLoc.READYR);
            MOT.Move(eAxis.PX_PICK, p1.Position, 250, p1.Acc, false, false, false);
            DialogResult = DialogResult.OK;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (CheckSafty() == false) return;

            //Z-check
            var z = MOT.GetPZPos(ePZLoc.READY);
            var zpos = MOT.getPositionOffset(z);
            if (zpos >= 0.5)
            {
                UTIL.MsgE("Raise the Z axis and try again");
                return;
            }

            //오른쪽프린터 뭉치가 준비위치가 아니면 오류
            var m1 = MOT.GetRMPos(eRMLoc.READY);
            if (MOT.getPositionMatch(m1) == false)
            {
                UTIL.MsgE("Printer attachment is not in ready position.\nCannot move as collision may occur");
                return;
            }

            //도어가 열려있다면 경고메세지를 표시한다.
            if (DIO.isSaftyDoorF(0, true) == false)
            {
                if (UTIL.MsgQ("Door is open. Do you want to move the motion?") != DialogResult.Yes) return;
            }

            var p1 = MOT.GetPXPos(ePXLoc.PICKOFFR);
            MOT.Move(eAxis.PX_PICK, p1.Position, 250, p1.Acc, false, false, false);
            DialogResult = DialogResult.OK;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            PUB.mot.MoveStop("pmove", (int)eAxis.PX_PICK);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //jog left
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //jog right
        }

        private void button6_MouseDown(object sender, MouseEventArgs e)
        {
            //조그시작


            var bt = sender as Button;
            if (bt.Text.Equals("▼"))
                PUB.mot.JOG((int)eAxis.PZ_PICK, arDev.MOT.MOTION_DIRECTION.Positive, AR.SETTING.Data.JOG_Speed, AR.SETTING.Data.JOG_Acc);
            else if (bt.Text.Equals("▲"))
                PUB.mot.JOG((int)eAxis.PZ_PICK, arDev.MOT.MOTION_DIRECTION.Negative, AR.SETTING.Data.JOG_Speed, AR.SETTING.Data.JOG_Acc);
            else if (bt.Text.Equals("◀"))
                PUB.mot.JOG((int)eAxis.PX_PICK, arDev.MOT.MOTION_DIRECTION.Negative, AR.SETTING.Data.JOG_Speed, AR.SETTING.Data.JOG_Acc);
            else if (bt.Text.Equals("▶"))
                PUB.mot.JOG((int)eAxis.PX_PICK, arDev.MOT.MOTION_DIRECTION.Positive, AR.SETTING.Data.JOG_Speed, AR.SETTING.Data.JOG_Acc);
        }

        private void button6_MouseUp(object sender, MouseEventArgs e)
        {
            //마우스 놓으면 멈춤
            PUB.mot.MoveStop("pmove", (short)eAxis.PX_PICK);
            PUB.mot.MoveStop("pmove", (short)eAxis.PZ_PICK);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            //왼쪽검증취소
            //	if (PUB.flag.get(eVarBool.RDY_VISION0) == 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.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));
            UpdateDatabase(eWorkPort.Left);
            DialogResult = DialogResult.OK;
        }

        private void button10_Click(object sender, EventArgs e)
        {
            //왼쪽검증취소
            //if (PUB.flag.get(eVarBool.RDY_VISION0) == 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.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));

            UpdateDatabase(eWorkPort.Right);
            DialogResult = DialogResult.OK;
        }

        void UpdateDatabase(eWorkPort vidx)
        {
            var itemdata = vidx == eWorkPort.Left ? PUB.Result.ItemDataL : PUB.Result.ItemDataR;

            var sql = "select top 1 * from K4EE_Component_Reel_Result where JGUID = @jguid";
            var dr = DBHelper.Get<DataSet1.K4EE_Component_Reel_ResultDataTable>(sql, new SqlParameter("jguid", itemdata.guid)).FirstOrDefault();
            if (dr == null)
            {
                var ermsg = string.Format("Cannot find the following guid, unable to change verification cancellation vidx={2},guid={0},sid={1}", itemdata.guid, itemdata.VisionData.SID, vidx);
                PUB.AddDebugLog(ermsg, true);
                PUB.log.AddE(ermsg);
            }
            else
            {
                DBHelper.UpdateWhere("K4EE_Component_Reel_Result",
                    new Dictionary<string, object>
                    {
                        { "ANGLE", itemdata.VisionData.ApplyAngle },
                        { "PRNVALID", 0 },
                        { "REMARK", "Verification cancelled" }
                    },
                    new Dictionary<string, object>
                    {
                        { "idx", dr.idx }
                    });

                //dr.ANGLE = itemdata.VisionData.ApplyAngle; //210331 - 도중에 사용자 angle 이 있다면 그것이 적용되었음
                //dr.PRNVALID = false;
                //dr.REMARK = "검증취소";
                //db.SaveChanges();
            }

        }

        private void button11_Click(object sender, EventArgs e)
        {
            //관리위치L
            MoveMangePos(0);
        }

        private void button13_Click(object sender, EventArgs e)
        {
            //관리위치
            MoveMangePos(2);
        }

        Boolean ManPosL = false;
        Boolean ManPosR = false;

        void MoveMangePos(int vidx)
        {
            if (PUB.sm.Step != eSMStep.IDLE)
            {
                UTIL.MsgE("Available only in standby state");
                return;
            }


            var Xpos = DIO.GetIOInput(eDIName.PICKER_SAFE);// MOT.getPositionMatch(MOT.GetPXPos(ePXLoc.PICKON), 1);
            if (Xpos == false)
            {
                UTIL.MsgE("Available only when picker is in center position");
                return;
            }

            

            Task.Run(new Action(() =>
            {
                //Z축을 Ready 위치로 이동한다.
                DateTime dt;
                if (vidx == 0)
                {   
                    //printer picker cylinder check
                    while(DIO.GetIOInput(eDIName.L_CYLUP)==false)
                    {
                        var dorlt = DIO.checkDigitalO(eDOName.L_CYLDN, new TimeSpan(1), false);
                        if (dorlt == eNormalResult.False)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        else if( dorlt == eNormalResult.Error)
                        {
                            PUB.log.AddE("l_cylup check error");
                            return;
                        }
                    }

                    var zPos = MOT.GetLZPos(eLZLoc.READY).Clone();
                    zPos.Speed = 100;
                    MOT.Move(zPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(zPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }


                    var mPos = MOT.GetLMPos(eLMLoc.PRINTL07).Clone();
                    mPos.Speed = 100;
                    MOT.Move(mPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(mPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }


                    var zPos2 = MOT.GetLZPos(eLZLoc.PICKOFF);
                    var tPos = (zPos2.Position / 2f);
                    MOT.Move(eAxis.PL_UPDN, tPos, 100, zPos.Acc);
                    ManPosL = true;
                }
                else
                {
                    while (DIO.GetIOInput(eDIName.R_CYLUP) == false)
                    {
                        var dorlt = DIO.checkDigitalO(eDOName.R_CYLDN, new TimeSpan(1), false);
                        if (dorlt == eNormalResult.False)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        else if (dorlt == eNormalResult.Error)
                        {
                            PUB.log.AddE("r_cylup check error");
                            return;
                        }
                    }

                    var zPos = MOT.GetRZPos(eRZLoc.READY).Clone();
                    zPos.Speed = 100;
                    MOT.Move(zPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(zPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }

                    var mPos = MOT.GetRMPos(eRMLoc.PRINTL07).Clone();
                    mPos.Speed = 100;
                    MOT.Move(mPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(mPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }

                    var zPos2 = MOT.GetRZPos(eRZLoc.PICKOFF);
                    var tPos = (zPos2.Position / 2f);
                    MOT.Move(eAxis.PR_UPDN, tPos, 100, zPos.Acc);
                    ManPosR = true;
                }

            }));
        }

        private void button12_Click(object sender, EventArgs e)
        {
            var Xpos = DIO.GetIOInput(eDIName.PICKER_SAFE);
            if (Xpos == false)
            {
                UTIL.MsgE("Available only when picker is in center position");
                return;
            }

            //위치복귀
            PosRecover(0);
            PosRecover(2);
        }

        void PosRecover(int vidx)
        {
            Task.Run(new Action(() =>
            {
                //Z축을 Ready 위치로 이동한다.
                DateTime dt;
                if (vidx == 0)
                {
                    while (DIO.GetIOInput(eDIName.L_CYLUP) == false)
                    {
                        var dorlt = DIO.checkDigitalO(eDOName.L_CYLDN, new TimeSpan(1), false);
                        if (dorlt == eNormalResult.False)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        else if (dorlt == eNormalResult.Error)
                        {
                            PUB.log.AddE("l_cylup check error");
                            return;
                        }
                    }

                    var zPos = MOT.GetLZPos(eLZLoc.READY).Clone();
                    zPos.Speed = 100;
                    MOT.Move(zPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(zPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }

                    var mPos = MOT.GetLMPos(eLMLoc.READY).Clone();
                    mPos.Speed = 100;
                    MOT.Move(mPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(mPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }
                    ManPosL = false;
                }
                else
                {
                    while (DIO.GetIOInput(eDIName.R_CYLUP) == false)
                    {
                        var dorlt = DIO.checkDigitalO(eDOName.R_CYLDN, new TimeSpan(1), false);
                        if (dorlt == eNormalResult.False)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        else if (dorlt == eNormalResult.Error)
                        {
                            PUB.log.AddE("R_cylup check error");
                            return;
                        }
                    }

                    var zPos = MOT.GetRZPos(eRZLoc.READY).Clone();
                    zPos.Speed = 100;
                    MOT.Move(zPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(zPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }

                    var mPos = MOT.GetRMPos(eRMLoc.READY).Clone();
                    mPos.Speed = 100;
                    MOT.Move(mPos);
                    dt = DateTime.Now;
                    while (MOT.getPositionMatch(zPos) == false)
                    {
                        var ts = DateTime.Now - dt;
                        if (ts.TotalSeconds > 30) break;
                        System.Threading.Thread.Sleep(10);
                    }

                    ManPosR = false;
                }

            }));
        }

        private void timer1_Tick(object sender, EventArgs e)
        {





            //X축 피커는 Z축이 원점,limit 에 걸려있거나 home 위치 근처라면 가능한다
            if (PUB.mot.IsHomeSet((int)eAxis.PZ_PICK) == false)
            {
                //Z축 홈이 안잡힌 상태에는 원점 센서 혹은 리밋이 걸린경우 이동가능한다
                if (PUB.mot.IsOrg((int)eAxis.PZ_PICK) || PUB.mot.IsLimitN((int)eAxis.PZ_PICK))
                    button6.Enabled = true;
                else
                    button6.Enabled = false;
            }
            else
            {
                //Z축 홈이 잡혀있다면 현재 위치는 ready 위에 있어야 한다.
                var PosZ = MOT.GetPZPos(ePZLoc.READY);
                var OffZ = MOT.getPositionOffset(PosZ);
                button6.Enabled = OffZ < 1;
            }
            button7.Enabled = button6.Enabled;

            AR.VAR.BOOL[eVarBool.Enable_PickerMoveX] = button6.Enabled;

            var doorsafef = DIO.isSaftyDoorF();
            var allsafe = PUB.mot.HasHomeSetOff == false && doorsafef == true;
            this.button11.Enabled = allsafe;
            this.button12.Enabled = allsafe;
            this.button13.Enabled = allsafe;

            //모션홈이 안잡혀있다면 이동 기능은 OFf한다
            btl.Enabled = allsafe;
            btlw.Enabled = allsafe;
            btc.Enabled = allsafe;
            btrw.Enabled = allsafe;
            btr.Enabled = allsafe;

            this.button8.BackColor = DIO.GetIOInput(eDIName.PICKER_SAFE) ? Color.Lime : Color.Tomato;


        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            PUB.PrinterL.TestPrint(AR.SETTING.Data.DrawOutbox, "", "");
            PUB.log.Add("Temporary print L:" + PUB.PrinterL.LastPrintZPL);
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            PUB.PrinterR.TestPrint(AR.SETTING.Data.DrawOutbox, "", "");
            PUB.log.Add("Temporary print R:" + PUB.PrinterR.LastPrintZPL);
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            if (PUB.mot.IsHomeSet((int)eAxis.PZ_PICK) == false)
            {
                UTIL.MsgE("Z home operation is not completed. Please perform HOME first");
                return;
            }
            if (UTIL.MsgQ("Do you want to move picker Z-axis to coordinate:0?") != DialogResult.Yes) return;
            MOT.Move(eAxis.PZ_PICK, 0, 500, 1000, false, false, false);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            var dlg = UTIL.MsgQ("Do you want to proceed with picker Z-axis home search?");
            if (dlg != DialogResult.Yes) return;

            MOT.Home("Management", eAxis.PZ_PICK, false);
        }

        private void button3_Click_1(object sender, EventArgs e)
        {

        }
    }
}
