using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using Project.Commands;
using AR;
namespace Project
{
    public partial class FMain
    {
        public void _STEP_HOME_FULL_START(eSMStep step)
        {
            //ClearBarcode();
            //Pub.popup.needClose = true; // Pub.popup.CloseAll();

            //181225
            if (PUB.dio.IsInit)
                DIO.SetBuzzer(false);

            if (PUB.mot.IsInit)
            {
                //알람클리어작업
                if (PUB.mot.HasServoAlarm)
                {
                    PUB.mot.SetAlarmClearOn();
                    System.Threading.Thread.Sleep(200);
                    PUB.mot.SetAlarmClearOff();
                }
            }

            HomeSuccessTime = DateTime.Parse("1982-11-23");


            //홈모드로 전환
            hmi1.Scean = UIControl.HMI.eScean.MotHome;
            hmi1.arHomeProgress[0] = 0;
            hmi1.arHomeProgress[1] = 0;
            hmi1.arHomeProgress[2] = 0;
            hmi1.arHomeProgress[3] = 0;
            hmi1.arHomeProgress[4] = 0;
            hmi1.arHomeProgress[5] = 0;
            hmi1.arHomeProgress[6] = 0;

            //실린더 상태 복귀
            DIO.SetOutput(eDOName.PRINTL_FWD, false);
            DIO.SetOutput(eDOName.PRINTR_FWD, false);
            DIO.SetOutput(eDOName.L_CYLDN, false);
            DIO.SetOutput(eDOName.R_CYLDN, false);
        }
        public StepResult _STEP_HOME_FULL(eSMStep step, TimeSpan stepTime, TimeSpan seqTime)
        {
            //전체 홈 시간을 체크한다.
            if (stepTime.TotalSeconds >= AR.SETTING.Data.Timeout_HomeSearch)
            {
                PUB.Result.SetResultMessage(eResult.TIMEOUT, eECode.HOME_TIMEOUT, eNextStep.NOTHING, AR.SETTING.Data.Timeout_HomeSearch); //, eECode.(eResult.HomeTimeout,msg ,false);
                return StepResult.Error;
            }

            //*********************
            //**    하드웨어 조건 확인
            //*********************
            if (CheckHomeProcess_HW_Available(false) == false)
            {

                return StepResult.Error;
            }


            int idx = 1;
            var cmdIndex = step;

            //Check X Safty Area
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //안전위치 센서가 안들어와잇으면 오류 처리한다
                if (DIO.GetIOInput(eDIName.PICKER_SAFE) == false)
                {
                    PUB.Result.SetResultMessage(eResult.MOTION,
                        eECode.MOTX_SAFETY,
                        eNextStep.ERROR,
                        eAxis.PL_MOVE, PUB.mot.ErrorMessage);
                    return StepResult.Error;
                }


                //포트 모두내리기(221013 - 박형철)
                if (VAR.BOOL[eVarBool.Use_Conveyor] == false && AR.SETTING.Data.Disable_HomePortDown == false)
                {
                    DIO.SetPortMotor(0, eMotDir.CCW, true, "HOME");
                    DIO.SetPortMotor(1, eMotDir.CCW, true, "HOME");
                    DIO.SetPortMotor(2, eMotDir.CCW, true, "HOME");
                }

                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }



            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //홈 설정여부플래그 OFF
                for (short i = 0; i < PUB.mot.DeviceCount; i++)
                {
                    if (PUB.mot.IsUse(i) == false) continue;
                    PUB.mot.SetHomeSet(i, false);
                }

                //부저 OFF
                DIO.SetBuzzer(false);

                //프린터부착헤드 후진
                if (DIO.GetIOInput(eDIName.L_PICK_BW) == false)
                    DIO.SetOutput(eDOName.PRINTL_FWD, false);

                if (DIO.GetIOInput(eDIName.R_PICK_BW) == false)
                    DIO.SetOutput(eDOName.PRINTR_FWD, false);


                if (DIO.GetIOInput(eDIName.L_CYLUP) == false)
                    DIO.SetOutput(eDOName.L_CYLDN, false);

                if (DIO.GetIOInput(eDIName.R_CYLUP) == false)
                    DIO.SetOutput(eDOName.R_CYLDN, false);

                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //피커실린더 상승
            if (PUB.sm.seq.Get(step) == idx++)
            {
                DIO.SetOutput(eDOName.L_CYLDN, false);
                DIO.SetOutput(eDOName.R_CYLDN, false);
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }
            if (PUB.sm.seq.Get(step) == idx++)
            {
                if (AR.SETTING.Data.Enable_PickerCylinder)
                {

                    if (DIO.checkDigitalO(eDIName.L_CYLUP, seqTime, true, timeoutcode: eECode.PICKER_LCYL_NOUP) != eNormalResult.True) return StepResult.Wait;
                    if (DIO.checkDigitalO(eDIName.R_CYLUP, seqTime, true, timeoutcode: eECode.PICKER_RCYL_NOUP) != eNormalResult.True) return StepResult.Wait;
                }
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //프린터 부착헤드 후진 검사
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //프린터부착헤드 후진
                if (DIO.GetIOInput(eDIName.L_PICK_BW) == false)
                {
                    if (stepTime.TotalSeconds > 5)
                    {
                        PUB.Result.SetResultMessage(eResult.MOTION, eECode.PRINTER_LPICKER_NOBW, eNextStep.PAUSE);
                    }
                    return StepResult.Wait;
                }
                if (DIO.GetIOInput(eDIName.R_PICK_BW) == false)
                {
                    if (stepTime.TotalSeconds > 5)
                    {
                        PUB.Result.SetResultMessage(eResult.MOTION, eECode.PRINTER_RPICKER_NOBW, eNextStep.PAUSE);
                    }
                    return StepResult.Wait;
                }

                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //프린터 부착헤드 후진 검사
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //프린터부착헤드 후진
                if (AR.SETTING.Data.Enable_PickerCylinder)
                {
                    if (DIO.GetIOInput(eDIName.L_CYLUP) == false)
                    {
                        if (stepTime.TotalSeconds > 5)
                        {
                            PUB.Result.SetResultMessage(eResult.MOTION, eECode.PRINTER_LPRINTER_NOUP, eNextStep.PAUSE);
                        }
                        return StepResult.Wait;
                    }
                    if (DIO.GetIOInput(eDIName.R_CYLUP) == false)
                    {
                        if (stepTime.TotalSeconds > 5)
                        {
                            PUB.Result.SetResultMessage(eResult.MOTION, eECode.PRINTER_RPRINTER_NOUP, eNextStep.PAUSE);
                        }
                        return StepResult.Wait;
                    }
                }
                else
                {
                    //전진이  들어와  있다면  오류  로한다
                    if (DIO.GetIOInput(eDIName.L_CYLDN))
                    {
                        PUB.Result.SetResultMessage(eResult.MOTION, eECode.PRINTER_LPRINTER_NOUP, eNextStep.PAUSE);
                        return StepResult.Wait;
                    }
                    if (DIO.GetIOInput(eDIName.R_CYLDN))
                    {
                        PUB.Result.SetResultMessage(eResult.MOTION, eECode.PRINTER_RPRINTER_NOUP, eNextStep.PAUSE);
                        return StepResult.Wait;
                    }
                }

                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }



            //피커의 Z축을 우선 진행
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                var rlt1 = MOT.Home("RUN_SAFTY_HOME", eAxis.PZ_PICK);
                if (rlt1 == false)
                {
                    PUB.Result.SetResultMessage(eResult.MOTION,
                        eECode.MOT_HSEARCH,
                        eNextStep.ERROR,
                         eAxis.PL_UPDN, PUB.mot.ErrorMessage);
                    return StepResult.Error;
                }
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //Z축 안전위치 대기
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (PUB.mot.IsHomeSet((short)eAxis.PZ_PICK) == false && PUB.mot.IsLimitN((short)eAxis.PZ_PICK) == false && PUB.mot.IsOrg((short)eAxis.PZ_PICK) == false)
                {
                    System.Threading.Thread.Sleep(10);
                    return StepResult.Wait;
                }
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //프린터의 Z축을 먼저 한다 221013
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                var rlt1 = MOT.Home("RUN_SAFTY_HOME", eAxis.PL_UPDN);
                var rlt2 = MOT.Home("RUN_SAFTY_HOME", eAxis.PR_UPDN);
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //Z축 안전위치 대기
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (PUB.mot.IsHomeSet((short)eAxis.PL_UPDN) == false && PUB.mot.IsLimitN((short)eAxis.PL_UPDN) == false && PUB.mot.IsOrg((short)eAxis.PL_UPDN) == false)
                {
                    System.Threading.Thread.Sleep(10);
                    return StepResult.Wait;
                }
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }


            //Z축 안전위치 대기
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (PUB.mot.IsHomeSet((short)eAxis.PR_UPDN) == false && PUB.mot.IsLimitN((short)eAxis.PR_UPDN) == false && PUB.mot.IsOrg((short)eAxis.PR_UPDN) == false)
                {
                    System.Threading.Thread.Sleep(10);
                    return StepResult.Wait;
                }
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }



            //각 프린터의 Y,Z 축의 홈을 진행한다.
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //유효성 검사를 하지 않는다.. 하게되면 오류남 201208
                var rlt1 = MOT.Home("RUN_SAFTY_HOME", eAxis.PL_MOVE, false);
                var rlt2 = MOT.Home("RUN_SAFTY_HOME", eAxis.PR_MOVE, false);
                //var rlt3 = MOT.Home("RUN_SAFTY_HOME", eAxis.PL_UPDN, false);
                //var rlt4 = MOT.Home("RUN_SAFTY_HOME", eAxis.PR_UPDN, false);
                if (rlt1 == false)
                {
                    PUB.Result.SetResultMessage(eResult.MOTION,
                        eECode.MOT_HSEARCH,
                        eNextStep.ERROR,
                        eAxis.PL_MOVE, PUB.mot.ErrorMessage);
                    return StepResult.Error;
                }
                if (rlt2 == false)
                {
                    PUB.Result.SetResultMessage(eResult.MOTION,
                        eECode.MOT_HSEARCH,
                        eNextStep.ERROR,
                        eAxis.PR_MOVE, PUB.mot.ErrorMessage);
                    return StepResult.Error;
                }
                //if (rlt3 == false)
                //{
                //	PUB.Result.SetResultMessage(eResult.MOTION,
                //		eECode.MOT_HSEARCH,
                //		eNextStep.ERROR,
                //		eAxis.PL_UPDN, PUB.mot.ErrorMessage);
                //	return StepResult.Error;
                //}
                //if (rlt4 == false)
                //{
                //	PUB.Result.SetResultMessage(eResult.MOTION,
                //		eECode.MOT_HSEARCH,
                //		eNextStep.ERROR,
                //		eAxis.PR_UPDN, PUB.mot.ErrorMessage);
                //	return StepResult.Error;
                //}
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //프린터축의 Y,Z축이 완료되기를 기다린다.
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                if (PUB.mot.IsHomeSet((short)eAxis.PL_MOVE) &&
                PUB.mot.IsHomeSet((short)eAxis.PR_MOVE) &&
                PUB.mot.IsHomeSet((short)eAxis.PL_UPDN) &&
                PUB.mot.IsHomeSet((short)eAxis.PR_UPDN))
                {
                    //현재위치를 0으로 설정한다.
                    PUB.mot.ClearPosition((int)eAxis.PL_MOVE);
                    PUB.mot.ClearPosition((int)eAxis.PR_MOVE);

                    //var p1 = MOT.GetLMPos(eLMLoc.READY);
                    //MOT.Move(eAxis.PL_MOVE, p1.Position, 200, 500, false, false, false);

                    //var p2 = MOT.GetRMPos(eRMLoc.READY);
                    //p2.Speed = 100;
                    //MOT.Move(eAxis.PR_MOVE, p2.Position, 200, 500, false, false, false);

                    PUB.sm.seq.Update(cmdIndex);
                }
                return StepResult.Wait;
            }

            //실린더를OFF한다 - 210207
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                DIO.SetOutput(eDOName.PRINTL_FWD, false);
                DIO.SetOutput(eDOName.PRINTR_FWD, false);
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //실린더 OFF 확인 - 210207
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //IO가 완료되지 안항ㅆ다면 대기한다
                if (DIO.checkDigitalO(eDIName.L_PICK_BW, seqTime, true) != eNormalResult.True) return StepResult.Wait;
                if (DIO.checkDigitalO(eDIName.R_PICK_BW, seqTime, true) != eNormalResult.True) return StepResult.Wait;
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }



            //프린터 move 축 안전지대로이동
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                var PosLM = MOT.GetLMPos(eLMLoc.READY);
                var PosRM = MOT.GetRMPos(eRMLoc.READY);
                PosLM.Speed = 200;
                PosRM.Speed = 200;
                MOT.Move((eAxis)PosLM.Axis, PosLM.Position, PosLM.Speed, PosLM.Acc, false, false, false);
                MOT.Move((eAxis)PosRM.Axis, PosRM.Position, PosRM.Speed, PosRM.Acc, false, false, false);
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //프린터 move 축 안전지대로이동
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                var PosLM = MOT.GetLMPos(eLMLoc.READY);
                var PosRM = MOT.GetRMPos(eRMLoc.READY);
                PosLM.Speed = 250;
                PosRM.Speed = 250;
                if (MOT.CheckMotionPos(seqTime, PosLM, "MOT_HOME", false) == false) return StepResult.Wait;
                if (MOT.CheckMotionPos(seqTime, PosRM, "MOT_HOME", false) == false) return StepResult.Wait;
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //Theta 홈
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //회전축은 잡지 않는다
                PUB.mot.SetHomeSet((int)eAxis.Z_THETA, true);
                PUB.mot.ClearPosition((int)eAxis.Z_THETA);
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //피커-X축 홈
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                var rlt1 = MOT.Home("RUN_SAFTY_HOME", eAxis.PX_PICK, false);
                if (rlt1 == false)
                {
                    PUB.Result.SetResultMessage(eResult.MOTION,
                      eECode.MOT_HSEARCH,
                      eNextStep.ERROR,
                      eAxis.PX_PICK, PUB.mot.ErrorMessage);
                    return StepResult.Error;
                }
                PUB.sm.seq.Update(cmdIndex);
                return StepResult.Wait;
            }

            //모든축의 완료여부 확인
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //모든축이 완료되었다면 완료처리를 한다.
                if (PUB.mot.IsHomeSet((short)eAxis.PX_PICK))
                {
                    //완료처리
                    PUB.mot.ClearPosition((int)eAxis.PX_PICK);
                    PUB.sm.seq.Update(cmdIndex);
                }
                return StepResult.Wait;
            }

            //X축 값 초기화확인
            if (PUB.sm.seq.Get(cmdIndex) == idx++)
            {
                //모든축이 완료되었다면 완료처리를 한다.
                var ts = PUB.sm.seq.GetTime(cmdIndex);
                if (ts.TotalSeconds >= 5)
                {
                    PUB.Result.SetResultMessage(eResult.MOTION,
                      eECode.MOT_HSEARCH,
                      eNextStep.ERROR,
                      eAxis.PX_PICK, PUB.mot.ErrorMessage);
                    return StepResult.Error;
                }
                else
                {
                    var XPos = PUB.mot.GetActPos((int)eAxis.PX_PICK);
                    if (Math.Abs(XPos) <= 0.1 && PUB.mot.IsMotion((int)eAxis.PX_PICK) == false)
                    {
                        PUB.sm.seq.Update(cmdIndex);
                    }
                }
                return StepResult.Wait;
            }

            //완료됨
            if (PUB.sm.seq.Get(step) == idx++)
            {
                //진공상태를 초기화 해준다.
                DIO.SetPrintLVac(ePrintVac.off, true);
                DIO.SetPrintRVac(ePrintVac.off, true);
                DIO.SetOutput(eDOName.PRINTL_AIRON, false);
                DIO.SetOutput(eDOName.PRINTR_AIRON, false);

                FlagClear(true);
                PUB.sm.SetNewStep(eSMStep.HOME_DELAY);
                return StepResult.Complete;
            }

            return StepResult.Complete;
        }

        void FlagClear(bool ClearItemOn)
        {
            PUB.log.AddAT($"Flag initialization({ClearItemOn})");
            //연관플래그 소거
            if (ClearItemOn)
            {
                PUB.flag.set(eVarBool.FG_PK_ITEMON, false, "POSRESET");
                PUB.flag.set(eVarBool.FG_PL_ITEMON, false, "POSRESET");
                PUB.flag.set(eVarBool.FG_PR_ITEMON, false, "POSRESET");
                PUB.flag.set(eVarBool.FG_PORTL_ITEMON, false, "POSRESET");
                PUB.flag.set(eVarBool.FG_PORTR_ITEMON, false, "POSRESET");
            }


            PUB.flag.set(eVarBool.FG_OK_PRINTL, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_OK_PRINTR, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PRINTL, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PRINTR, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_RDY_PORT_PC, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PORT_PL, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PORT_PR, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_RDY_PX_LPICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PX_RPICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PX_PICKONWAITL, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PX_PICKONWAITR, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_SET_DATA_PORT0, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_SET_DATA_PORT2, false, "POSRESET");
            //PUB.flag.set(eVarBool.SCR_JOBFINISH, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_WAIT_PAPERDETECTL, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_WAIT_PAPERDETECTR, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_END_VISIONL, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_END_VISIONR, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_PRC_VISIONL, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_PRC_VISIONR, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_CMD_YP_LPICKON, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_CMD_YP_LPICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_CMD_YP_RPICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_CMD_YP_RPICKON, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PZ_LPICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PZ_RPICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RDY_PZ_PICKON, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_RUN_PLM_PICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PRM_PICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PLM_PICKON, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PRM_PICKON, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_RUN_PLZ_PICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PRZ_PICKOF, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PLZ_PICKON, false, "POSRESET");
            PUB.flag.set(eVarBool.FG_RUN_PRZ_PICKON, false, "POSRESET");

            PUB.flag.set(eVarBool.FG_RUN_LEFT, false, "POSREST");
            PUB.flag.set(eVarBool.FG_RUN_RIGHT, false, "POSREST");
            //VAR.BOOL[eVarBool.JOB_BYPASS_LEFT] = false;
            //VAR.BOOL[eVarBool.JOB_BYPASS_RIGHT] = false;
            //VAR.STR[eVarString.JOB_BYPASS_SID] = string.Empty;
            //VAR.STR[eVarString.JOB_TYPE] = string.Empty;

            //retry소거 230510
            VAR.BOOL[eVarBool.JOB_PickON_Retry] = false;
            VAR.BOOL[eVarBool.VisionL_Retry] = false;
            VAR.BOOL[eVarBool.VisionR_Retry] = false;
            VAR.BOOL[eVarBool.wait_for_keyence] = false;
            VAR.BOOL[eVarBool.wait_for_keyenceL] = false;
            VAR.BOOL[eVarBool.wait_for_keyenceR] = false;
            VAR.BOOL[eVarBool.JOB_Empty_SIDConvertInfo] = false;

            //busy 플래그 제거
            PUB.iLockCVL.set((int)eILockCV.BUSY, false, "POSREST");
            PUB.iLockCVR.set((int)eILockCV.BUSY, false, "POSREST");
            PUB.iLockCVL.set((int)eILockCV.VISION, false, "POSREST");
            PUB.iLockCVR.set((int)eILockCV.VISION, false, "POSREST");

            VAR.I32[eVarInt32.RIGT_ITEM_COUNT] = 0;
            VAR.I32[eVarInt32.LEFT_ITEM_COUNT] = 0;
        }

    }
}
