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

namespace Project
{
    public partial class FMain
    {
        async public Task<bool> _SM_RUN_STARTCHKSW(bool isFirst, TimeSpan stepTime)
        {
            var mc = PUB.Result.mModel;
            var mv = PUB.Result.vModel;

            double free = 0;
            var savepath = PUB.getSavePath(out free);
            if (free < 3.0)
            {
                string msg = "FREE SPACE ERROR\n" +
                    "Insufficient disk space (3%) to proceed with the work\n" +
                 "Storage path: {0}\n" +
                 "Please delete data or check the deletion cycle in settings";
                msg = string.Format(msg, AR.SETTING.Data.GetDataPath());
                PUB.popup.setMessage(msg);
                DIO.SetBuzzer(true);
                PUB.sm.SetNewStep(eSMStep.IDLE);
                return false;
            }



            if (PUB.Result.isSetmModel == false)
            {
                string msg = "Motion model not selected\nPlease check the 'MOTION' item in the work model";
                PUB.popup.setMessage(msg);
                DIO.SetBuzzer(true);
                PUB.sm.SetNewStep(eSMStep.IDLE);
                return false;
            }


            //모션의 모든 위치가 원점이 아니라면 홈 초기화를 요청한다.
            var initMsg = "";

            if (initMsg != "")
            {
                PUB.popup.setMessage(initMsg);
                DIO.SetBuzzer(true);
                PUB.sm.SetNewStep(eSMStep.IDLE);
                return false;
            }

            //모델정보가 설정되어있는지 확인
            if (PUB.Result == null ||
                PUB.Result.vModel == null ||
                PUB.Result.vModel.Title.isEmpty())
            {
                PUB.Result.SetResultMessage(eResult.SETUP, eECode.NOMODELV, eNextStep.ERROR);
                return false;
            }

            //모션모델자동선택 230823
            var motionmode = VAR.BOOL[eVarBool.Use_Conveyor] ? "Conveyor" : "Default";
            if (PUB.SelectModelM(motionmode) == false)
            {
                PUB.Result.SetResultMessage(eResult.SETUP, eECode.NOMODELM, eNextStep.ERROR);
                return false;
            }

            //모델정보가 설정되어있는지 확인
            if (PUB.Result == null ||
                PUB.Result.mModel == null ||
                PUB.Result.mModel.Title.isEmpty())
            {
                PUB.Result.SetResultMessage(eResult.SETUP, eECode.NOMODELM, eNextStep.ERROR);
                return false;
            }

            //ECS데이터확인 230823
            var conv = VAR.BOOL[eVarBool.Use_Conveyor];
            if (conv)
            {
                var sidinfo = await PUB.UpdateSIDInfo();
                var systembypass = SETTING.Data.SystemBypass;
                if (systembypass == false && sidinfo.Item1 == false)
                {
                    PUB.Result.SetResultMessage(eResult.SETUP, eECode.NOECSDATA, eNextStep.ERROR, sidinfo.Item2);
                    return false;
                }
                //else if (systembypass == false && sidinfo.Item3 < 1)
                //{
                //    PUB.Result.SetResultMessage(eResult.SETUP, eECode.NOECSDATAACTIVE, eNextStep.ERROR, sidinfo.Item2);
                //    return false;
                //}
            }

            //SID변환정보  필요  230823
            //이값도  테이블에서  실시간으로  조회되므로  미리  불러올  필요  없다

            //사용자추가정보  필요  230823
            //기존에  사용하던  사용자  추가 정보
            //ECS정보가  수신되면  기존 TABLE 을  삭제하는  구조이므로  병행할수  없음
            //데이터는  테이블에서  실시간으로  조 회됨

            //사용자스텝실행
            if (PUB.flag.get(eVarBool.FG_USERSTEP))
            {
                PUB.flag.set(eVarBool.FG_USERSTEP, false, "STACHKSW");
                PUB.log.AddI("H/W inspection ignore function disabled due to work start");
            }

            //Auto Reel Out 250926
            PUB.Result.AutoReelOut = PUB.Result.vModel.AutoOutConveyor > 0;

            //공용변수초기화
            PUB.log.Add("Common variable (count) values initialized");
            VAR.I32.Clear((int)eVarInt32.LPickOfCount);
            VAR.I32.Clear((int)eVarInt32.LPickOnCount);
            VAR.I32.Clear((int)eVarInt32.RPickOfCount);
            VAR.I32.Clear((int)eVarInt32.RPickOnCount);
            VAR.I32.Clear((int)eVarInt32.PickOfCount);
            VAR.I32.Clear((int)eVarInt32.PickOnCount);
            VAR.I32.Clear((int)eVarInt32.PickOnRetry);  //221102


            PUB.flag.set(eVarBool.FG_RUN_LEFT, false, "POSREST");
            PUB.flag.set(eVarBool.FG_RUN_RIGHT, false, "POSREST");

            VAR.BOOL[eVarBool.JOB_Empty_SIDConvertInfo] = false;
            VAR.BOOL[eVarBool.FG_AUTOOUTCONVL] = false;
            VAR.BOOL[eVarBool.FG_AUTOOUTCONVR] = false;
            AutoConvOutTimeL = new DateTime(1982, 11, 23);
            AutoConvOutTimeR = new DateTime(1982, 11, 23);

            PUB.Result.ItemDataL.Clear("START_CHKSW");
            PUB.Result.ItemDataC.Clear("START_CHKSW");
            PUB.Result.ItemDataR.Clear("START_CHKSW");

            var modelName = PUB.Result.vModel.Title;
            lock (PUB.Result.BCDPatternLock)
            {
                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}");
            }


            //변환SID SID확인여부데이터 삭제
            PUB.Result.DTSidConvertEmptyList.Clear();
            PUB.Result.DTSidConvertMultiList.Clear();

            PUB.Result.JobStartTime = DateTime.Now;
            warninactivelist.Clear();

            //작업락기능해제
            LockPK.Set();
            LockUserL.Set();
            LockUserR.Set();


            return true;
        }
    }
}
