using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using AR;

namespace Project
{
    public partial class FMain
    {
        /// <summary>
        /// 키엔스가 실패했을때 재시도 하는 작업이다
        /// 중앙에서 잡고 79도 틀고, 내려 놓고 피한다
        /// </summary>
        /// <param name="target"></param>
        /// <param name="cmdIndex"></param>
        /// <returns></returns>
        public Boolean PICKER_RETRY(eWorkPort target, eSMStep cmdIndex)
        {
            UInt16 idx = 1;
            var mv = PUB.Result.vModel;
            var mc = PUB.Result.mModel;
            var funcName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            var seqTime = PUB.sm.seq.GetTime(cmdIndex);
            var msgType = (Class.eStatusMesage)target;
            var iLockX = PUB.iLock[(int)eAxis.PX_PICK];
            var iLockZ = PUB.iLock[(int)eAxis.PZ_PICK];
            var PickerRetryCount = AR.VAR.I32[(int)eVarInt32.PickOnRetry];
            //####################################################
            //###	인터락 확인
            //####################################################
            Boolean MotMoveX = PUB.mot.IsMotion((int)eAxis.PX_PICK);
            Boolean MotMoveZ = PUB.mot.IsMotion((int)eAxis.PZ_PICK);
            if (iLockX.IsEmpty() == false && MotMoveX)
            {
                var locklistX = MOT.GetActiveLockList(eAxis.PX_PICK, iLockX);
                PUB.mot.MoveStop("ILock(" + string.Join(",", locklistX) + ")", (int)eAxis.PX_PICK);
            }

            if (iLockZ.IsEmpty() == false && MotMoveZ)
            {
                var locklistZ = MOT.GetActiveLockList(eAxis.PZ_PICK, iLockZ);
                PUB.mot.MoveStop("ILock(" + string.Join(",", locklistZ) + ")", (int)eAxis.PZ_PICK);
            }

            //####################################################
            //###	작업시작
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                PUB.log.Add($"[{target}] Picker RETRY work started ({PickerRetryCount}/{AR.SETTING.Data.RetryPickOnMaxCount})");

                //기존자료를 모두 삭제 한다 221102
                if (PUB.Result.ItemDataC != null && PUB.Result.ItemDataC.VisionData != null && PUB.Result.ItemDataC.VisionData.barcodelist != null)
                {
                    lock (PUB.Result.ItemDataC.VisionData.barcodelist)
                    {
                        PUB.Result.ItemDataC.VisionData.Clear(funcName, true);
                    }
                }

                AR.VAR.BOOL[eVarBool.JOB_PickON_Retry] = true;
                PUB.mot.ClearPosition((int)eAxis.Z_THETA);
                PUB.sm.seq.Update(cmdIndex);
                DIO.SetPickerVac(false);
                return false;
            }

            //####################################################
            //###	Z를 먼저 Ready 로 이동
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (iLockZ.IsEmpty() == false) return false;
                var Pos = MOT.GetPZPos(ePZLoc.READY);
                if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                DIO.SetPickerVac(true);
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	X를 픽온위치로 이동
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (iLockX.IsEmpty() == false) return false;
                var Pos = MOT.GetPXPos(ePXLoc.PICKON);
                if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                DIO.SetPickerVac(true);
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	Z축 내리기 조건확인
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                var PortRDY = PUB.flag.get(eVarBool.FG_RDY_PORT_PC);
                if (PortRDY == false) return false;
                DIO.SetPickerVac(true);
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	Z축을 내린다.
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (iLockZ.IsEmpty() == false) return false;
                var Pos = MOT.GetPZPos(ePZLoc.PICKON);
                if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                VAR.I32[eVarInt32.PickOnCount] += 1;
                //PUB.flag.set(eVarBool.PK_ITEMON, true, funcName);
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	100ms 대기
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (seqTime.TotalMilliseconds < 100) return false;
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	Z축을 올린다.
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (iLockZ.IsEmpty() == false) return false;
                var Pos = MOT.GetPZPos(ePZLoc.READY);
                if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                //PUB.flag.set(eVarBool.PK_ITEMON, true, funcName);
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }


            //####################################################
            //###	현재위치에서 79도 회전
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //속도값만 취한다
                var Pos = MOT.GetPTPos(ePTLoc.READY);
                Pos.Position = PUB.mot.GetActPos((int)eAxis.Z_THETA) + AR.SETTING.Data.RetryPickOnAngle;
                VAR.DBL[(int)eVarDBL.ThetaPosition] = Pos.Position;
                MOT.Move(Pos);
                //if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	현재위치에서 79도 회전
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //속도값만 취한다
                var Pos = MOT.GetPTPos(ePTLoc.READY);
                Pos.Position = VAR.DBL[(int)eVarDBL.ThetaPosition];
                if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }


            //####################################################
            //###	Z를 pick on 위치로 1/3 지점으로 이동한다
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (iLockZ.IsEmpty() == false) return false;
                var PosS = MOT.GetPZPos(ePZLoc.READY);
                var PosT = MOT.GetPZPos(ePZLoc.PICKON);
                var offset = (int)(Math.Abs(PosT.Position - PosS.Position) * 0.7f);
                PosS.Position += offset;    //시작위치에서 절반만 이동한다
                if (MOT.CheckMotionPos(seqTime, PosS, funcName) == false) return false;
                DIO.SetPickerVac(false); //릴을 내려 놓는다
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	Z축을 올린다.
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (iLockZ.IsEmpty() == false) return false;
                var Pos = MOT.GetPZPos(ePZLoc.READY);
                if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                DIO.SetPickerVac(false); //백큠을 꺼서 원복한다
                hmi1.arVar_Port[1].AlignReset(); //231013
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }


            //####################################################
            //###	키엔스를 읽어야 하므로 피해준다
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (iLockX.IsEmpty() == false) return false;

                sPositionData Pos;
                if (target == eWorkPort.Left) Pos = MOT.GetPXPos(ePXLoc.READYL);
                else Pos = MOT.GetPXPos(ePXLoc.READYR);

                //theta모터 위치 초기화
                PUB.mot.ClearPosition((int)eAxis.Z_THETA);

                if (MOT.CheckMotionPos(seqTime, Pos, funcName) == false) return false;
                PUB.log.AddAT($"###### Retry work avoidance movement completed ({target})");
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }

            //####################################################
            //###	비젼데이터를 초기화 해준다.
            //####################################################
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                PUB.log.Add($"Deleting vision data due to retry completion");
                PUB.Result.ItemDataC.VisionData.Clear(funcName, true);
                AR.VAR.BOOL[eVarBool.JOB_PickON_Retry] = false;
                PUB.sm.seq.Update(cmdIndex);
                return false;
            }
                       
            //일련번호 초기화 해준다
            PUB.sm.seq.Clear(cmdIndex);
            return true;
        }

    }
}