using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using Project.StateMachine;
using COMM;
using System.Diagnostics;
using AR;

namespace Project
{
    public partial class fMain
    {
        Dictionary<string, string> synlist;
        int synidx;
        public Boolean _SM_RUN_SYNC(bool isFirst, TimeSpan stepTime)
        {
            var idx = 1;
            if (PUB.sm.RunStepSeq == idx++)
            {
                // return true;
                UpdateProgressStatus(stepTime.TotalSeconds, 5, "SYNC : 장치 연결(MAIN) 확인 중");
                if (PUB.AGV.IsOpen == false)
                {
                    //agv connect
                    var rlt = ConnectSerialPort(PUB.AGV, PUB.setting.Port_AGV, PUB.setting.Baud_AGV,
                         eVarTime.LastConn_AGV, eVarTime.LastConnTry_AGV, eVarTime.LastRecv_AGV);
                    if (rlt == false)
                    {
                        //존재하지 않는 포트라면 sync를 벗어난다
                        PUB.log.AddE($"AGV포트({PUB.setting.Port_AGV}) 가 존재하지않아 SYNC를 중단합니다");
                        PUB.sm.SetNewStep(eSMStep.IDLE);
                    }
                }
                else if (PUB.AGV.IsValid == true)
                {
                    //설정모드 진입
                    VAR.BOOL[eVarBool.FLAG_SETUP] = true;
                    LastCommandTime = DateTime.Now;

                    PUB.sm.UpdateRunStepSeq();
                }
                else
                {
                    UpdateProgressStatus(stepTime.TotalMilliseconds, 10000.0, "wait");
                    if (stepTime.TotalSeconds >= 10)
                    {
                        PUB.log.AddE("시간초과로 인해 Sync 작업이 실패되었습니다");
                        PUB.sm.SetNewStep(eSMStep.IDLE);
                    }
                }
                return false;
            }
            else if (PUB.sm.RunStepSeq == idx++)
            {
                //동기화 명령 생성
                synlist = new Dictionary<string, string>();
                synlist.Add("SSH", PUB.setting.SPD_H.ToString("0000"));   //           PUB.AGV.AGVCommand(item.Key, item.Value);
                synlist.Add("SSM", PUB.setting.SPD_M.ToString("0000"));
                synlist.Add("SSL", PUB.setting.SPD_L.ToString("0000"));

                synlist.Add("SSS", PUB.setting.SPD_S.ToString("0000"));
                synlist.Add("SRS", PUB.setting.SPD_R.ToString("0000"));

                synlist.Add("SPK", PUB.setting.PID_PH.ToString("0000"));
                synlist.Add("SPM", PUB.setting.PID_PM.ToString("0000"));
                synlist.Add("SPL", PUB.setting.PID_PL.ToString("0000"));

                synlist.Add("SIK", PUB.setting.PID_IH.ToString("0000"));
                synlist.Add("SIM", PUB.setting.PID_IM.ToString("0000"));
                synlist.Add("SIL", PUB.setting.PID_IL.ToString("0000"));

                synlist.Add("SDK", PUB.setting.PID_DH.ToString("0000"));
                synlist.Add("SDM", PUB.setting.PID_DM.ToString("0000"));
                synlist.Add("SDL", PUB.setting.PID_DL.ToString("0000"));

                synlist.Add("SPS", PUB.setting.PID_PS.ToString("0000"));
                synlist.Add("SIS", PUB.setting.PID_IS.ToString("0000"));
                synlist.Add("SDS", PUB.setting.PID_DS.ToString("0000"));

                //추가 230110
                synlist.Add("SCK", PUB.setting.SCK.ToString("0000"));
                synlist.Add("SSK", PUB.setting.SSK.ToString("0000"));
                synlist.Add("STT", PUB.setting.STT.ToString("0000"));
                //synlist.Add("SBN", PUB.setting.ChargerID.ToString("0000"));

                synlist.Add("SGS", PUB.setting.GDSValue.ToString("0000"));
                VAR.I32[eVarInt32.SyncItemCount] = synlist.Count;


                PUB.AddEEDB($"SYNC시작({PUB.Result.TargetPos})");

                synidx = 0;
                PUB.sm.UpdateRunStepSeq();
                return false;
            }
            else if (PUB.sm.RunStepSeq == idx++)
            {
                //잠시 대기
                var ts = DateTime.Now - LastCommandTime;
                if (ts.TotalSeconds > 0.15)
                {
                    PUB.sm.UpdateRunStepSeq();
                }
                return false;
            }
            else if (PUB.sm.RunStepSeq == idx++)
            {
                //통신 확인되었으므로 설정값들을 
                if (synidx < synlist.Count)
                {
                    var item = synlist.ElementAt(synidx);
                    UpdateProgressStatus(stepTime.TotalSeconds, 5, $"SYNC :{item.Key}");
                    PUB.AGV.AGVCommand(item.Key, item.Value);

                    // 캔버스에 동기화 상태 표시
                    if (PUB._mapCanvas != null)
                    {
                        float progress = (float)synidx / VAR.I32[eVarInt32.SyncItemCount];
                        PUB._mapCanvas.SetSyncStatus("장비 설정 동기화 중...", progress, $"항목: {item.Key} ({synidx + 1}/{synlist.Count})");
                    }
                }
                LastCommandTime = DateTime.Now;
                PUB.sm.UpdateRunStepSeq();
                return false;
            }
            else if (PUB.sm.RunStepSeq == idx++)
            {
                if (synidx < synlist.Count)
                {
                    var ts = DateTime.Now - LastCommandTime;
                    var item = synlist.ElementAt(synidx);
                    UpdateProgressStatus(stepTime.TotalSeconds, 5, $"SYNC 변경 확인 중 :{item.Key}");
                    if (PUB.AGV.ACKData.Equals(item.Key))
                    {
                        synidx += 1;
                        if (ts.TotalSeconds < 0.15) PUB.sm.UpdateRunStepSeq(-2);  //싱크중에 추가 지연시간 확보
                        else PUB.sm.UpdateRunStepSeq(-1);
                        LastCommandTime = DateTime.Now;
                    }
                    else
                    {
                        if (ts.TotalSeconds > 1)
                        {
                            PUB.AGV.AGVCommand(item.Key, item.Value);
                            LastCommandTime = DateTime.Now;
                            Console.WriteLine($"RE.send Sync : {item.Key}:{item.Value}");
                        }
                    }
                }
                else PUB.sm.UpdateRunStepSeq();
                return false;
            }
            else if (PUB.sm.RunStepSeq == idx++)
            {
                PUB.AddEEDB($"SYNC완료({PUB.Result.TargetPos})");
                UpdateProgressStatus(stepTime.TotalSeconds, 5, "SYNC : 완료");

                // 동기화 완료 시 캔버스 모드 복귀
                if (PUB._mapCanvas != null)
                    PUB._mapCanvas.SetSyncStatus("동기화 완료!", 1.0f, "잠시 후 메인 화면으로 이동합니다.");

                LastCommandTime = DateTime.Now;
                PUB.sm.UpdateRunStepSeq();
                return false;
            }
            return true;
        }
    }
}
