using System.Linq;
using AR;
using AGVNavigationCore.Models;
using Project.StateMachine;
using System.Windows.Forms;
using System;
using System.Collections.Generic;

namespace Project.Dialog
{
    public partial class fACSCommand : Form
    {
        public fACSCommand()
        {
            InitializeComponent();
        }

       
        private void btnGoto_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn == null) return;

            var targetAlias = btn.Text.Trim();
            var targetNode = PUB._mapCanvas.Nodes.FirstOrDefault(t => t.AliasName.ToUpper() == targetAlias.ToUpper());

            if (targetNode == null)
            {
                // Fallback for Buffer names which might have spaces
                targetNode = PUB._mapCanvas.Nodes.FirstOrDefault(t => t.AliasName.ToUpper().Replace(" ", "") == targetAlias.ToUpper().Replace(" ", ""));
            }

            if (targetNode == null)
            {
                UTIL.MsgE($"대상 노드를 찾을 수 없습니다: {targetAlias}");
                return;
            }

            // Goto 명령 데이터: RFID 문자열
            var data = System.Text.Encoding.Default.GetBytes(targetNode.RfidId.ToString());
            ExecuteRemoteCommand(ENIGProtocol.AGVCommandHE.Goto, data);
        }

        private void btnWork_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn == null) return;

            ENIGProtocol.AGVCommandHE cmd;
            switch (btn.Text)
            {
                case "PickOn Enter": cmd = ENIGProtocol.AGVCommandHE.PickOnEnter; break;
                case "PickOff Enter": cmd = ENIGProtocol.AGVCommandHE.PickOffEnter; break;
                case "Pickon Exit": cmd = ENIGProtocol.AGVCommandHE.PickOnExit; break;
                case "PickOff Exit": cmd = ENIGProtocol.AGVCommandHE.PickOffExit; break;
                default: return;
            }

            ExecuteRemoteCommand(cmd);
        }

        private void btnAction_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn == null) return;

            switch (btn.Text)
            {
                case "Turn Left":
                    ExecuteRemoteCommand(ENIGProtocol.AGVCommandHE.LTurn);
                    break;
                case "Turn Right":
                    ExecuteRemoteCommand(ENIGProtocol.AGVCommandHE.RTurn);
                    break;
                case "Mark Stop":
                    ExecuteRemoteCommand(ENIGProtocol.AGVCommandHE.MarkStop);
                    break;
                case "Charge":
                    // ChargeControl: 1=On
                    ExecuteRemoteCommand(ENIGProtocol.AGVCommandHE.ChargeControl, (byte)1);
                    break;
            }
        }

        private void fACSCommand_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// ACS로부터 수신된 패킷인 것처럼 시뮬레이션하여 메인 폼의 로직을 실행합니다.
        /// </summary>
        private void ExecuteRemoteCommand(ENIGProtocol.AGVCommandHE cmd, params byte[] data)
        {
            // XBEE 패킷 시뮬레이션
            var packet = new ENIG.Packet();
            packet.ID = 0; // ACS ID
            packet.Command = (byte)cmd;

            // 데이터 설정 (TargetID: PUB.setting.XBE_ID)
            var buffer = new List<byte>();
            buffer.Add((byte)PUB.setting.XBE_ID);
            if (data != null) buffer.AddRange(data);
            packet.Data = buffer.ToArray();

            var args = new ENIG.EEProtocol.DataEventArgs { ReceivedPacket = packet };

            var mainForm = Application.OpenForms.OfType<fMain>().FirstOrDefault();
            if (mainForm != null)
            {
                // fMain.cs 내의 XBE_ProtocReceived를 호출하기 위해 리플렉션 사용
                var method = typeof(fMain).GetMethod("XBE_ProtocReceived", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                if (method != null)
                {
                    method.Invoke(mainForm, new object[] { null, args });
                }
                else
                {
                    UTIL.MsgE("명령 처리 메서드(XBE_ProtocReceived)를 찾을 수 없습니다.");
                }
            }
            else
            {
                UTIL.MsgE("메인 폼 인스턴스를 찾을 수 없습니다.");
            }
        }

    }
}
