using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using arCtl;
using Project.StateMachine;
using COMM;
using AR;
using AGVNavigationCore.Models;

namespace Project
{

    public partial class fMain
    {
        private void AGV_Message(object sender, arDev.Narumi.MessageEventArgs e)
        {
            if (e.MsgType == arDev.arRS232.MessageType.Normal)

                PUB.logagv.AddE(e.Message);
            else if (e.MsgType == arDev.arRS232.MessageType.Normal)

                PUB.logagv.Add(e.Message);
            else if (e.MsgType == arDev.arRS232.MessageType.Recv)
            {
                if (e.Message.Substring(1).StartsWith("STS") == false)
                    PUB.logagv.Add("AGV-RX", e.Message);
            }
            else if (e.MsgType == arDev.arRS232.MessageType.Send)
                PUB.logagv.Add("AGV-TX", e.Message);
            else
            {

                PUB.logagv.Add(e.MsgType.ToString(), e.Message);
            }
        }


        bool _charging = false;
        private void AGV_DataReceive(object sender, arDev.Narumi.DataEventArgs e)
        {
            try
            {
                //데이터 파싱
                switch (e.DataType)
                {
                    case arDev.Narumi.DataType.STS:
                        {
                            //마크센서 확인
                            var chg_mark1 = PUB.AGV.signal.GetChanged(arDev.Narumi.Signal.eflag.mark_sensor_1);
                            var chg_mark2 = PUB.AGV.signal.GetChanged(arDev.Narumi.Signal.eflag.mark_sensor_1);
                            var chg_run = PUB.AGV.system1.GetChanged(arDev.Narumi.SystemFlag1.eflag.agv_run);
                            var chg_stop = PUB.AGV.system1.GetChanged(arDev.Narumi.SystemFlag1.eflag.agv_stop);
                            //if (chg_run && PUB.AGV.system1.agv_run) PUB.Speak("이동을 시작 합니다");
                            VAR.BOOL[eVarBool.AGVDIR_UP] = PUB.AGV.data.Direction == 'B';
                            VAR.BOOL[eVarBool.AGV_ERROR] = PUB.AGV.error.Value > 0;
                            VAR.BOOL[eVarBool.EMERGENCY] = PUB.AGV.error.Emergency;

                            ////모터방향 입력
                            //if (PUB.AGV.data.Direction == 'B')
                            //    PUB.mapctl.Manager.agv.Current_Motor_Direction = AGVControl.AgvDir.Backward;
                            //else
                            //    PUB.mapctl.Manager.agv.Current_Motor_Direction = AGVControl.AgvDir.Forward;

                            ////현재 속도
                            //if (PUB.AGV.data.Speed == 'H')
                            //    PUB.mapctl.Manager.agv.CurrentSpeed = AGVControl.AgvSpeed.High;
                            //else if (PUB.AGV.data.Speed == 'M')
                            //    PUB.mapctl.Manager.agv.CurrentSpeed = AGVControl.AgvSpeed.Middle;
                            //else if (PUB.AGV.data.Speed == 'L')
                            //    PUB.mapctl.Manager.agv.CurrentSpeed = AGVControl.AgvSpeed.Low;
                            //else if (PUB.AGV.data.Speed == 'S')
                            //    PUB.mapctl.Manager.agv.CurrentSpeed = AGVControl.AgvSpeed.MarkStop;

                            ////이동방향
                            //if (PUB.AGV.data.Sts == 'S')
                            //    PUB.mapctl.Manager.agv.CurrentSTS = AGVControl.AgvSts.Straight;
                            //else if (PUB.AGV.data.Sts == 'L')
                            //    PUB.mapctl.Manager.agv.CurrentSTS = AGVControl.AgvSts.Left;
                            //else if (PUB.AGV.data.Sts == 'R')
                            //    PUB.mapctl.Manager.agv.CurrentSTS = AGVControl.AgvSts.Right;


                            //PUB.mapctl.Manager.agv.IsMoving = PUB.AGV.system1.agv_run;
                            //PUB.mapctl.Manager.agv.IsMarkCheck = PUB.AGV.system1.Mark1_check || PUB.AGV.system1.Mark2_check;

                            if (PUB.AGV.signal.mark_sensor == false)
                            {
                                if (VAR.BOOL[eVarBool.MARK_SENSOROFF] == false)
                                {
                                    VAR.BOOL[eVarBool.MARK_SENSOROFF] = true;
                                    VAR.TIME[eVarTime.MarkSensorOff] = DateTime.Now;
                                    PUB.log.Add($"마크센서off를 설정");
                                }
                            }
                            else
                            {
                                if (VAR.BOOL[eVarBool.MARK_SENSOROFF] == true)
                                {
                                    VAR.BOOL[eVarBool.MARK_SENSOROFF] = false;
                                    VAR.TIME[eVarTime.MarkSensorOff] = DateTime.Now;
                                    PUB.log.Add($"마크센서off를 해제");
                                }
                            }


                            //차징상태변경
                            if (_charging != PUB.AGV.system1.Battery_charging)
                            {
                                if (PUB.AGV.system1.Battery_charging)
                                {
                                    VAR.TIME[eVarTime.ChargeStart] = DateTime.Now;
                                    PUB.logagv.Add($"충전시작:{VAR.TIME[eVarTime.ChargeStart]}");
                                }
                                _charging = PUB.AGV.system1.Battery_charging;
                            }

                            //배터리충전상태
                            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA] != PUB.AGV.system1.Battery_charging)
                            {
                                PUB.log.Add($"충전상태전환 {PUB.AGV.system1.Battery_charging}");
                                VAR.BOOL[eVarBool.FLAG_CHARGEONA] = PUB.AGV.system1.Battery_charging;
                            }
                            //자동충전해제시 곧바로 수동 충전되는 경우가 있어 자동 상태를 BMS에 넣는다 230118
                            PUB.BMS.AutoCharge = PUB.AGV.system1.Battery_charging;

                            if (PUB.AGV.error.Charger_pos_error != VAR.BOOL[eVarBool.CHG_POSERR])
                            {
                                if (PUB.AGV.error.Charger_pos_error)
                                {
                                    PUB.Speak(Lang.충전기위치오류);
                                }
                                VAR.BOOL[eVarBool.CHG_POSERR] = PUB.AGV.error.Charger_pos_error;
                            }

                            if (VAR.BOOL[eVarBool.MARK_SENSOROFF] == true && PUB.AGV.signal.mark_sensor == false)
                            {
                                //현재 활성화된 위치를 꺼준다
                                if (this.ctlPos1.GetPositionActive(PUB.Result.CurrentPos))
                                {
                                    var ts = VAR.TIME.RUN(eVarTime.MarkSensorOff);
                                    if (ts.TotalSeconds >= 2)
                                    {
                                        ctlPos1.SetPositionDeActive();
                                        PUB.log.Add($"현재 활성위치를 해제 함");
                                    }
                                }

                            }

                            //나르미가  멈췄다면  다음  마크  이동  기능이 OFF 된다
                            if (PUB.AGV.system1.agv_stop)
                                VAR.BOOL[eVarBool.NEXTSTOP_MARK] = false;

                            if (VAR.BOOL[eVarBool.MARK_SENSOR] != PUB.AGV.signal.mark_sensor)
                            {
                                if (PUB.AGV.signal.mark_sensor)
                                {
                                    //현재위치를 확정한다
                                    var curact = ctlPos1.GetPositionActive(PUB.Result.CurrentPos);
                                    if (curact == false)
                                    {
                                        PUB.log.Add($"마크센서로인해 현재위치 설정완료:{PUB.Result.CurrentPos}");
                                        ctlPos1.SetPositionActive(PUB.Result.CurrentPos);
                                        ctlPos1.SetDirection("");
                                        ctlPos1.Invalidate();
                                    }
                                }
                                VAR.BOOL[eVarBool.MARK_SENSOR] = PUB.AGV.signal.mark_sensor;
                            }
                        }
                        break;
                    case arDev.Narumi.DataType.TAG:
                        {
                            //자동 실행 중이다.
                            PUB.log.Add($"AGV 태그수신 : {PUB.AGV.data.TagNo}");
                            PUB.Result.LastTAG = PUB.AGV.data.TagNo.ToString();

                            //POT/NOT 보면 일단 바로 멈추게한다
                            if (PUB.Result.CurrentPos == ePosition.POT || PUB.Result.CurrentPos == ePosition.NOT)
                            {
                                var logEMsg = $"Stop by [POT/NOT]";
                                PUB.AGV.AGVMoveStop(logEMsg);
                                PUB.log.AddE(logEMsg);
                            }

                            //virtual agv setting
                            var CurrentNode = PUB._mapNodes.FirstOrDefault(t => t.RfidId.Equals(PUB.Result.LastTAG, StringComparison.OrdinalIgnoreCase));
                            if (CurrentNode == null)
                            {
                                //없는 노드는 자동으로 추가한다
                                var newNodeId = $"AUTO_{PUB.Result.LastTAG}";
                                var newNode = new MapNode
                                {
                                    NodeId = newNodeId,
                                    RfidId = PUB.Result.LastTAG,
                                    Name = $"자동추가_{PUB.Result.LastTAG}",
                                    Type = NodeType.Normal,                                    
                                    Position = new Point(100, 100), // 기본 위치
                                    IsActive = true,
                                    DisplayColor = Color.Orange, // 자동 추가된 노드는 오렌지색으로 표시
                                    CreatedDate = DateTime.Now,
                                    ModifiedDate = DateTime.Now
                                };

                                // 맵 노드 리스트에 추가
                                PUB._mapNodes.Add(newNode);

                                // 캔버스에 노드 반영 (재설정)
                                PUB._mapCanvas.Nodes = PUB._mapNodes;

                                // 로그 기록
                                PUB.log.AddI($"RFID:{PUB.Result.LastTAG} 노드를 자동 추가했습니다 (NodeId: {newNodeId})");

                                // CurrentNode에 새로 생성한 노드 할당
                                CurrentNode = newNode;
                            }
                            else
                            {
                                //모터방향 확인해서 UI와 AGV클래스에 적용한다
                                var MotDireciton = PUB.AGV.data.Direction == 'B' ? AGVNavigationCore.Models.AgvDirection.Backward : AGVNavigationCore.Models.AgvDirection.Forward;
                                PUB._mapCanvas.SetAGVPosition(PUB.setting.MCID, CurrentNode, MotDireciton);
                                PUB._virtualAGV.SetPosition(CurrentNode, MotDireciton);
                            }

                            //태그를 읽었다면 상태를 바로 전송한다
                            PUB.XBE.SendStatus();
                        }
                        break;
                    case arDev.Narumi.DataType.ACK:
                        PUB.logagv.Add($"AGV_[ACK]Receive : {PUB.AGV.ACKData}");
                        break;
                    default:
                        PUB.logagv.Add($"AGV_DataReceive : {e.DataType}");
                        break;

                }

                //이 후 상황을 예측한다
                var command = PUB._virtualAGV.Predict();
                var preditMSG = $"Motor:{command.Motor},Magnet:{command.Magnet},Speed:{command.Speed} : {command.Reason}";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AGV_DataReceive] {ex.Message}");
            }
        }
    }
}
