using ENIG;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace AGVEmulator
{
    public class DevXBE : AR.Dev.RS232
    {
        private EEProtocol proto;
        public event EventHandler<EEProtocol.DataEventArgs> ProtocReceived;

        public DevXBE()
        {
            proto = new EEProtocol();
            proto.OnDataReceived += Proto_OnDataReceived;
            proto.OnMessage += Proto_OnMessage;
        }
        ~DevXBE()
        {
            proto.OnDataReceived -= Proto_OnDataReceived;
            proto.OnMessage -= Proto_OnMessage;
        }

        public override bool ProcessRecvData(byte[] data)
        {
            return true;
        }

        protected override bool CustomParser(byte[] buf, out byte[] remainBuffer)
        {
            //여기서 최초데이터를 파싱한다
            remainBuffer = null;
            this.proto.ProcessReceivedData(buf);
            return false;

        }


        private void Proto_OnDataReceived(object sender, EEProtocol.DataEventArgs e)
        {
            var hexstrRaw = e.ReceivedPacket.RawData.HexString();
            var hexstr = e.ReceivedPacket.Data.HexString();
            var cmd = e.ReceivedPacket.Command.ToString("X2");
            var id = e.ReceivedPacket.ID.ToString("X2");

            var dataStr = System.Text.Encoding.Default.GetString(e.ReceivedPacket.Data);
            RaiseMessage(MessageType.Recv, $"ID:{id},CMD:{cmd},DATA:{hexstr}");
            ProtocReceived?.Invoke(this, e);
        }
        private void Proto_OnMessage(object sender, EEProtocol.MessageEventArgs e)
        {
            RaiseMessage(e.IsError, e.Message);
        }

        /// <summary>
        /// 목적지 태그번호 전송
        /// </summary>
        public void SendGotoTag(byte id, uint tag)
        {
            //var idSTR = id.ToString("X2");
            //var tagSTR = tag.ToString("0000");
            //var dataStr = $"{idSTR}{tagSTR}";
            var data = new List<byte>();
            data.Add(id);
            data.AddRange(System.Text.Encoding.Default.GetBytes(tag.ToString("0000")));
            Send(ENIGProtocol.AGVCommandHE.Goto, data.ToArray());
        }

        /// <summary>
        /// 카트를 가지러 들어간다
        /// </summary>
        /// <param name="id"></param>
        public void SendPickOnEnter(byte id)
        {
            var data = new List<byte>();
            data.Add(id);
            Send(ENIGProtocol.AGVCommandHE.PickOnEnter, data.ToArray());
        }

        /// <summary>
        /// 카트를 내려놓으로 들어간다
        /// </summary>
        /// <param name="id"></param>
        public void SendPickOffEnter(byte id)
        {
            var data = new List<byte>();
            data.Add(id);
            Send(ENIGProtocol.AGVCommandHE.PickOffEnter, data.ToArray());
        }

        /// <summary>
        /// 카트를 가지러 들어가서 나온다
        /// </summary>
        /// <param name="id"></param>
        public void SendPickOnExit(byte id)
        {
            var data = new List<byte>();
            data.Add(id);
            Send(ENIGProtocol.AGVCommandHE.PickOnExit, data.ToArray());
        }

        /// <summary>
        /// 카트를 내려놓으러 들어가서 나온다
        /// </summary>
        /// <param name="id"></param>
        public void SendPickOffExit(byte id)
        {
            var data = new List<byte>();
            data.Add(id);
            Send(ENIGProtocol.AGVCommandHE.PickOffExit, data.ToArray());
        }



        public void SendCurrentPos(byte id, uint tag)
        {
            var data = new List<byte>();
            data.Add(id);
            data.AddRange(System.Text.Encoding.Default.GetBytes(tag.ToString("0000")));
            Send(ENIGProtocol.AGVCommandHE.SetCurrent, data.ToArray());
        }
        private void Send(ENIGProtocol.AGVCommandHE Command, byte[] data)
        {
            byte id = 0;
            byte cmd = (byte)Command; //move to target
            var packet = proto.CreatePacket(id, cmd, data);
            if (WriteData(packet, false))
            {
                var hexstr =(data == null || data.Any()==false) ? string.Empty :  System.Text.Encoding.Default.GetString(data);
                RaiseMessage(MessageType.Send, $"ID:{id},CMD:{cmd},DATA:{hexstr}");
            }
        }


    }
}
